Second level Cache Perfomance - mysql

Recently I was studying some possibilities to improve my code , and I did some changes on it . I installed the hibernate configurations to use the second level cache, but the result of this improvement wasn't good enough .I was expecting a shortly time in my database queries. When I made some research after the implementation, the time was bigger than I had before this modification in my code . Even if I enable the cache query , my results don't change. What I saw after enable the query cache was worse time results . Another thing what I could see , was, if my tables has some relationship with another one , the search time increase a lot.
HibernateUtil
package com.journaldev.hibernate.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
System.out.println("Hibernate Configuration loaded");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
System.out.println("Hibernate serviceRegistry created");
SessionFactory sessionFactoryLocal = configuration.buildSessionFactory(serviceRegistry);
return sessionFactoryLocal;
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return sessionFactory;
}}
Employee
package com.journaldev.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name = "EMPLOYEE")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "emp_id")
private long id;
#Column(name = "emp_name")
private String name;
#Column(name = "emp_salary")
private double salary;
public Employee(String name) {
this.name = name;
}
public Employee() {
}}
Adress
package com.journaldev.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name = "ADDRESS")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Address {
#Id
#GeneratedValue
private long id;
#Column(name = "address_line1")
private String addressLine1;
#Column(name = "zipcode")
private String zipcode;
#Column(name = "city")
private String city;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Employee Relation Adress
package com.journaldev.hibernate.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name = "EMPLOYEE")
#Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "emp_id")
private long id;
#Column(name = "emp_name")
private String name;
#Column(name = "emp_salary")
private double salary;
#OneToOne(mappedBy = "employee")
#Cascade(value = org.hibernate.annotations.CascadeType.ALL)
private Address address;
public Employee(String name) {
this.name = name;
}
public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
Class teste
package com.journaldev.hibernate.main;
import org.hibernate.Session;
import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;
import java.util.Date;
public class HibernateEHCacheMain {
public static void main(String[] args) {
//insert10000();
// System.out.println("Temp Dir:" + System.getProperty("java.io.tmpdir"));
long init1 = new Date().getTime();
list10000WithCache();
long end1 = new Date().getTime();
long result1 = end1 - init1;
long init2 = new Date().getTime();
list10000WithCache();
long end2 = new Date().getTime();
long result2 = end2 - init2;
long init3 = new Date().getTime();
list10000WithCache();
//list10000WithoutCache();
long end3 = new Date().getTime();
long result3 = end3 - init3;
System.err.println("Result 1 : " + result1 + "\nResult 2 :" + result2 + "\nResult 3 :" + result3);
System.exit(1);
}
private static void insert10000() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
for (int i = 0; i < 10000; i++) {
session.save(new Employee(i + ""));
if (i % 20 == 0) {
session.flush();
session.clear();
}
}
session.getTransaction().commit();
session.close();
}
private static void list10000WithoutCache() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.createQuery("from Employee").list();
session.getTransaction().commit();
session.close();
}
private static void list10000WithCache() {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.createQuery("from Employee").setCacheable(true).list();
session.getTransaction().commit();
session.close();
}
}
Hibernate.cfg
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "classpath://org/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/mydb</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.default_batch_fetch_size">20</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<!-- For singleton factory -->
<!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property>
-->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- enable second level cache and query cache -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
<mapping class="com.journaldev.hibernate.model.Employee" />
<mapping class="com.journaldev.hibernate.model.Address" />
</session-factory>
</hibernate-configuration>
myehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
monitoring="autodetect" dynamicConfig="true">
<diskStore path="java.io.tmpdir/ehcache" />
<defaultCache maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120" diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU" statistics="true">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="employee" maxEntriesLocalHeap="10000" eternal="false"
timeToIdleSeconds="5" timeToLiveSeconds="10">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.internal.StandardQueryCache"
maxEntriesLocalHeap="5" eternal="false" timeToLiveSeconds="120">
<persistence strategy="localTempSwap" />
</cache>
<cache name="org.hibernate.cache.spi.UpdateTimestampsCache"
maxEntriesLocalHeap="5000" eternal="true">
<persistence strategy="localTempSwap" />
</cache>
</ehcache>

How Query Caching works ?
Query Cache is used to cache the results of a query. When the query cache is turned on, the results of the query are stored against the combination query and parameters. Every time the query is fired the cache manager checks for the combination of parameters and query. If the results are found in the cache, they are returned, otherwise a database transaction is initiated.
Why Query Cache should not use ?
As you can see, it is not a good idea to cache a query if it has a number of parameters, because then a single parameter can take a number of values. For each of these combinations the results are stored in the memory. This can lead to extensive memory usage.
They are many pitfalls in enabling query second level caching.Please go through this link.
I dont see any issues in your configuration.All you need to enable statistic on sessionfactory to find second level caching is working or not.
Statistics statistics = sessionFactory.getStatistics();
statistics.setStatisticsEnabled(true);
You can check below values
statistics.getEntityFetchCount()
statistics.getSecondLevelCacheHitCount()
statistics.getSecondLevelCachePutCount()
statistics.getSecondLevelCacheMissCount()
Go with this post for precise explanation on second level caching with statistics.

Related

What are the steps required to create spring boot project using database first approach? Database used here is MySQL

I am learning spring boot (for REST API). I have read spring boot documentation and other tutorials but all are based on creating database tables using entities (code first approach). One of the tutorials talked about JBoss(installed in from Eclipse marketplace). So I followed the tutorial and I was able to create entities, dao, pojo classes from database tables. But the tutorial doesn't talk about how to perform crud operations now. So I tried to perform some crud operation and I am getting errors.
UserController
package com.example.dbfirst.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.dbfirst.entities.User;
import com.example.dbfirst.service.UserService;
#RestController
public class UserController {
#Autowired
private UserService userService;
#RequestMapping("users/{id}")
public User getUser(#PathVariable("id") int id) {
return this.userService.getUser(id);
}
}
UserService
package com.example.dbfirst.service;
import javax.ejb.EJB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dbfirst.dao.UserHome;
import com.example.dbfirst.entities.User;
#Service
public class UserService {
//#Autowired
private UserHome userHome;
public User getUser(int id) {
userHome=new UserHome();
return this.userHome.findById(id);
}
}
User DAO class using JBoss and hibernate.cfg.xml
UserHome
package com.example.dbfirst.dao;
// Generated 25-Mar-2021, 4:50:30 pm by Hibernate Tools 5.2.12.Final
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import com.example.dbfirst.entities.User;
#Stateless
public class UserHome {
private static final Log log = LogFactory.getLog(UserHome.class);
#PersistenceContext
private EntityManager entityManager;
public void persist(User transientInstance) {
log.debug("persisting User instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void remove(User persistentInstance) {
log.debug("removing User instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public User findById(Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = entityManager.find(User.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
UserEntities
package com.example.dbfirst.entities;
// Generated 25-Mar-2021, 4:12:53 pm by Hibernate Tools 5.2.12.Final
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* User generated by hbm2java
*/
#Entity
#Table(name = "user", catalog = "mydb")
public class User implements java.io.Serializable {
private Integer id;
private String email;
private String password;
public User() {
}
public User(String email, String password) {
this.email = email;
this.password = password;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "email", length = 45)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "password", length = 45)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
User Pojo class
package com.example.dbfirst.pojo;
// Generated 25-Mar-2021, 4:09:56 pm by Hibernate Tools 5.2.12.Final
/**
* User generated by hbm2java
*/
public class User implements java.io.Serializable {
private Integer id;
private String email;
private String password;
public User() {
}
public User(String email, String password) {
this.email = email;
this.password = password;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
Now When I call "users/id" from POSTMAN, I am getting this error:
"status": 500,
"error": "Internal Server Error",
"message": "Cannot invoke \"javax.persistence.EntityManager.find(java.lang.Class, Object)\" because \"this.entityManager\" is null",
"path": "/users/2"
I might be missing some steps or I might have made some mistake somewhere.
It would be helpful if you can tell me the steps required to create spring boot project using database first approach (upto crud operation). You can also share some articles/link.
I have already looked at many articles to solve this issue. The reason I want database first approach are following:
I want to keep database part separate from spring project coding part (Don't want to mix them at such level)
I want to design database separately , completely independent of project type.
Thank you for your help.
In your case follow these steps:
Create your database table first.
Turn off auto-create and auto-update.
There is lot of unnecessary lines in your code.
Create only Entity class(add dto later)
Directly access repository from controller(remove service layer for now add later )
If have map columns to entity field properly other-wise it will cause errors(Use #Cloumn(name ="name")) for avoiding error and Use #Id for primary key.
You can refer:
Disable auto update in spring data jpa
https://spring.io/guides/gs/accessing-data-jpa/

How to correct sql statement to give correct result

I'm running a local MySQL Server on port 3306 with a schema "sys" featuring a table "users"
Now I have a small spring boot application to query all entries from that table.
Model for that table is:
package com.example.databaseneu.model;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Users {
#Id
// #Column(name = "id")
private int id;
// #Column(name = "name")
private String name;
// #Column(name = "salary")
private int salary;
// #Column(name = "team_name")
private String team_name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getTeam_name() {
return team_name;
}
public void setTeam_name(String team_name) {
this.team_name = team_name;
}}
The connection works, but the query doesnt seem to deliver the right result as I get the Whitelabel Error Page.
Query to get all elements from the table (autogenerated by repository)
Hibernate:
select
users0_.id as id1_0_,
users0_.name as name2_0_,
users0_.salary as salary3_0_,
users0_.team_name as team_nam4_0_
from
users users0_
So I'm uncertain if i defined the Entity wrong or something else alltogether
#Column Tag doesnt do the trick.
---Edit---
package com.example.databaseneu.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.example.databaseneu.model.Users;
import com.example.databaseneu.repository.UserRepository;
#Controller // This means that this class is a Controller
#RequestMapping(path = "/demo") // This means URL's start with /demo (after Application path)
public class MainController {
#Autowired
private UserRepository userRepository;
#GetMapping(path = "/add")
public #ResponseBody String addNewUser(#RequestParam String name, #RequestParam int salary,
#RequestParam String team_name) {
Users n = new Users();
n.setName(name);
n.setSalary(salary);
n.setTeam_name(team_name);
userRepository.save(n);
return "Saved";
}
#GetMapping(path = "/all")
public Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
So id navigate to localhost:8080/demo/all
You have written all correct expect for one thing. Mark your return-type with #ResponseBody annotation -- similar to your addNewUser method.
#GetMapping(path = "/all")
public #ResponseBody Iterable<Users> getAllUsers() {
return userRepository.findAll();
}}
Hopefully this should work. If you still face issues, post it here.

Hibernate Optimistic Lock with/without a Version not working

I have a legacy app that uses:
hibernate-3.5.5.jar
hibernate-jpa-2.0-api-1.0.0.jar
Spring 3.0.2
Tapestry 5.3.8
MySQL
Tomcat 7.0.64
It has a serious issue with multiple users updating the same table row at the same time and loosing the first update. Basically user A says "I want to own the record" (place my id in the record) and user B says "I want to own the record" the code being processed takes a bit of time. So user A gets it and then user B doesn't notice that user A had it and so user B gets it when he shouldn't have because user A already had it.
I've tried using:
#org.hibernate.annotations.Entity(dynamicUpdate = true, optimisticLock = OptimisticLockType.ALL)
on the Entity class for the table and watching the SQL that hibernate produces it never adds the table columns to the SQL update statement. It simply has update ... where id=?.
I've also tried adding a version column to the table in question and the Entity class and annotated the field with
#Version.
This has exactly the same effect as above, nothing in the generated SQL is using the version column. It never gets incremented either.
I'm guessing that I'm missing something with setting this up or there is something about the way the app uses hibernate that is keeping this from working as everything I have read says it should "Just Work".
appContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Configurer that replaces ${...} placeholders with values from a properties
file -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:app_jdbc.properties"/>
</bean>
<!-- Message source for this context, loaded from localized files -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>app_app</value>
<value>app_env</value>
<value>pdf</value>
</list>
</property>
</bean>
<!-- Define data source -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>${jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
<property name="defaultAutoCommit">
<value>${jdbc.autoCommit}</value>
</property>
<property name="maxActive">
<value>${dbcp.maxActive}</value>
</property>
<property name="maxWait">
<value>${dbcp.maxWait}</value>
</property>
</bean>
<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
...
<value>company.app.domain.Overtime</value>
...
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.query.substitutions">${hibernate.query.substitutions}</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative
to JTA) -->
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<!-- regular beans -->
<bean id="baseDao" class="vive.db.BaseHbDao">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
...
<bean id="overtimeDao" class="company.app.dataaccess.OvertimeDao">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
...
<!-- service beans -->
<bean id="appService" class="company.app.services.AppService">
<property name="baseDao"><ref local="baseDao"/></property>
...
</bean>
<!-- transaction advice -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* company.app.services.*Service.*(..))" />
<aop:advisor pointcut-ref="serviceOperation" advice-ref="txAdvice" />
</aop:config>
</beans>
Overtime Entity class:
package company.app.domain;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.OptimisticLockType;
#Entity
#Table(name = "over_time")
#org.hibernate.annotations.Entity(dynamicUpdate = true, optimisticLock = OptimisticLockType.ALL)
public class Overtime implements java.io.Serializable {
private static final long serialVersionUID = 7263309927526074109L;
#Id
#GeneratedValue(generator = "ot_gen")
#GenericGenerator(name = "ot_gen", strategy = "hilo", parameters = {
#Parameter(name = "table", value = "unique_key"), #Parameter(name = "column", value = "next_hi"),
#Parameter(name = "max_lo", value = "99") })
private Integer id;
#Deprecated
#Column(name = "from_time")
private Date fromTime;
#Deprecated
#Column(name = "to_time")
private Date toTime;
#Column(name = "fm_dttm")
private Long fromDttm;
#Column(name = "to_dttm")
private Long toDttm;
#Column(name = "post_dttm")
private Long postDttm;
private String dow;
private String shift;
#Column(name = "sub_groups")
private String subGroups;
#Column(name = "created_by")
private String createdBy;
#Column(name = "signed_up_by")
private String signedUpBy;
#Column(name = "signed_up_via")
private String signedUpVia;
#Column(name = "date_signed_up")
private Date dateSignedUp;
#Column(name = "signed_up_by_partner_username")
private String signedUpByPartnerUsername;
#Column(name = "signed_up_by_partner_ot_refno")
private String signedUpByPartnerOtRefNo;
private String comment;
private Integer status;
#Column(name = "title_abbrev")
private String titleAbbrev;
#Column(name = "record_status")
private String recordStatus;
#Column(name = "ref_no")
private String refNo;
#Column(name = "ref_id")
private String refId;
#Column(name = "misc_notes")
private String miscNotes;
#Column(name = "sends_notif_upon_posting")
private Boolean sendsNotificationUponPosting;
#Column(name = "notify_post_person_when_filled")
private Boolean notifyPostPersonWhenFilled;
#Column(name = "notify_others_when_filled")
private Boolean notifyOthersWhenFilled;
#Column(name = "vehicle_needed")
private Boolean vehicleNeeded;
#Column(name = "agency_id")
private Integer agencyId;
#Column(name = "schedule_id")
private Integer scheduleId;
#Column(name = "post_date")
private Date postDate;
#Column(name = "enrollment_opens_at")
private Date enrollmentOpensAt;
#Column(name = "enrollment_closes_at")
private Date enrollmentClosesAt;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "class_id")
private OvertimeClass overtimeClass;
public Overtime() {
}
//getters and setters
}
The Tapestry page class where the user tries to sign up for the overtime:
package company.app.pages;
import java.io.*;
import java.text.MessageFormat;
import java.util.*;
import org.apache.tapestry5.StreamResponse;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestGlobals;
import org.hibernate.StaleObjectStateException;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import vive.util.*;
import company.t5ext.LabelValueSelectModel;
import company.t5ext.components.DateTimeField;
import company.app.*;
import company.app.domain.*;
import company.app.services.CacheService;
import company.app.services.AppService;
import company.app.comparator.OtComparator;
#RequiresLogin
public class ListPostedOvertime {
#SessionState
#Property
private AppSessionState visit;
#Inject
private RequestGlobals requestGlobals;
#Inject
#Property
private AppService appService;
#Inject
private Request request;
void setupRender() {
...
}
// this method handle the case when a user tries to sign up for an overtime slot
void onSignUp(Integer overtimeId) {
// check to see if the OT has been deleted or modified or signed-up
Overtime ot = (Overtime)appService.getById(Overtime.class, overtimeId);
if (ot == null) {
visit.setOneTimeMessage("The overtime has already been deleted.");
return;
}
if (ot.getStatus() != null && ot.getStatus() != AppConst.OT_NEW) {
visit.setOneTimeMessage("The overtime has already been signed up. Please choose a different one to sign up.");
return;
}
...
try {
appService.validateOvertimeForUser(agency, user, ot);
appService.handleSignUpOvertime(agency, user, ot);
// log activity
String what = "Signed up for overtime " + ot.getRefNo() + ".";
appService.logActivity(user, AppConst.LOG_OVERTIME, what);
} catch(StaleObjectStateException e) {
visit.setOneTimeMessage("The overtime record has been changed by another user, please try again.");
return;
} catch(Exception e) {
visit.setOneTimeMessage(e.getMessage());
return;
}
...
}
}
The AppService class that is used by the Tapestry page to update the overtime record:
package company.app.services;
import java.io.Serializable;
import java.util.*;
import java.text.DecimalFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.support.ResourceBundleMessageSource;
import vive.db.BaseHbDao;
import vive.util.*;
import company.app.*;
import company.app.comparator.LeaveRequestComparator;
import company.app.comparator.UserOtInterestComparator;
import company.app.dataaccess.*;
import company.app.domain.*;
public class AppService
{
private Log log = LogFactory.getLog(this.getClass().getName());
private BaseHbDao baseDao;
private OvertimeDao otDao;
private MiscDao miscDao;
private ResourceBundleMessageSource msgSource;
/**
* Default constructor.
*/
public AppService() {
}
public void save(Object item) {
if (item != null) {
baseDao.save(item);
}
}
public void update(Object item) {
if (item != null) {
baseDao.update(item);
}
}
public void saveOrUpdate(Object item) {
if (item != null) {
baseDao.saveOrUpdate(item);
}
}
public void saveOrUpdateAll(Collection col) {
if (col != null) {
baseDao.saveOrUpdateAll(col);
}
}
public void delete(Object item) {
if (item != null) {
baseDao.delete(item);
}
}
public void deleteAll(Collection col) {
if (col != null) {
baseDao.deleteAll(col);
}
}
public Object getById(Class clazz, Serializable id) {
return baseDao.get(clazz, id);
}
public Object getById(Class clazz, Serializable id, LockMode lockMode) {
return baseDao.get(clazz, id, lockMode);
}
public void validateOvertimeForUser(Agency agency, User user, Overtime ot) throws Exception {
validateOvertimeForUser(agency.getId(), agency, user, ot);
}
public void validateOvertimeForUser(AgencyLite agency, User user, Overtime ot) throws Exception {
validateOvertimeForUser(agency.getId(), agency, user, ot);
}
public void handleSignUpOvertime(AgencyBase agency, User user, Integer otId) {
Overtime ot = (Overtime)getById(Overtime.class, otId);
handleSignUpOvertime(agency, user, ot);
}
public void handleSignUpOvertime(AgencyBase agency, User user, Overtime ot) {
handleSignUpOvertime(agency, user, ot, 1.0d);
}
public void handleSignUpOvertime(AgencyBase agency, User user, Integer otId, Double ptsPerOt) {
Overtime ot = (Overtime)getById(Overtime.class, otId);
handleSignUpOvertime(agency, user, ot, ptsPerOt);
}
public void handleSignUpOvertime(AgencyBase agency, User user, Overtime ot, Double ptsPerOt) {
handleSignUpOvertime(agency, user, ot, ptsPerOt, null, null);
}
public void handleSignUpOvertime(AgencyBase agency, User user, Overtime ot, Double ptsPerOt, String viaUsername, String viaName) {
Date today = new Date();
boolean isOtConfirmRequired = AppUtil.isTrue(agency.getOtConfirmRequired());
Integer otConfirmThreshold = 0;
if (agency.getOtConfirmThreshold() != null) {
otConfirmThreshold = agency.getOtConfirmThreshold();
}
long otInDays = (ot.getFromDttm() - today.getTime()) / AppConst.MILLIS_IN_DAY;
ot.setSignedUpBy(user.getUsername());
ot.setDateSignedUp(today);
ot.setSignedUpVia(viaUsername);
if (isOtConfirmRequired && otInDays >= otConfirmThreshold) {
ot.setStatus(AppConst.OT_PDG);
} else {
ot.setStatus(AppConst.OT_FIN);
}
saveOrUpdate(ot);
user.setLastOtSignupDate(today);
user.setPoints(AppUtil.addPoints(ptsPerOt, user.getPoints()));
saveOrUpdate(user);
...
// email notification sent from caller
}
...
}
The base class for all of the DAO classes:
package vive.db;
import java.io.Serializable;
import java.util.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import vive.XException;
import vive.util.XUtil;
/**
* The superclass for hibernate data access object.
*/
public class BaseHbDao extends HibernateDaoSupport implements BaseHbDaoInterface
{
private Log log;
public BaseHbDao() {
super();
log = LogFactory.getLog(getClass());
}
...
/**
* Save or update an object.
*/
public void saveOrUpdate(Object obj) {
getHibernateTemplate().saveOrUpdate(obj);
}
public void save(Object obj) {
getHibernateTemplate().save(obj);
}
public void update(Object obj) {
getHibernateTemplate().update(obj);
}
/**
* Delete an object.
*/
public void delete(Object obj) {
getHibernateTemplate().delete(obj);
}
/**
* Retrieve an object of the given id, null if it does not exist.
* Similar to "load" except that an exception will be thrown for "load" if
* the given record does not exist.
*/
public Object get(Class clz, Serializable id) {
return getHibernateTemplate().get(clz, id);
}
public Object get(Class clz, Serializable id, LockMode lockMode) {
return getHibernateTemplate().get(clz, id, lockMode);
}
...
public void flush() {
getHibernateTemplate().flush();
}
/**
* Retrieve a HB session.
* Make sure to release it after you are done with the session by calling
* releaseHbSession.
*/
public Session getHbSession() {
try {
return getSession();
} catch (Exception e) {
return null;
}
}
/**
* Release a HB Session
*/
public void releaseHbSession(Session sess) {
releaseSession(sess);
}
}
Okay I got it working!
First, I'm using the #Version annotation so I added a version column to the table with the problem.
alter table over_time add version INT(11) DEFAULT 0;
Second, add the Version annotation and member to the Entity class:
public class Overtime implements java.io.Serializable {
private static final long serialVersionUID = 7263309927526074109L;
#Id
#GeneratedValue(generator = "ot_gen")
#GenericGenerator(name = "ot_gen", strategy = "hilo", parameters = {
#Parameter(name = "table", value = "unique_key"), #Parameter(name = "column", value = "next_hi"),
#Parameter(name = "max_lo", value = "99") })
private Integer id;
#Version
#Column(name = "version")
private int version;
...
When I tried this the first couple of times I was using an Integer object not an int primitive for the version member of the class. I THINK this was the issue.
Also make sure that the other hibernate specific annotation is NOT on the entity class:
#org.hibernate.annotations.Entity(dynamicUpdate = true, optimisticLock = OptimisticLockType.ALL)
Third, the exception that gets thrown is not what any of the web sites I've read say it should be, so let's catch the one that really is thrown in the Tapestry page class that handles the user signing up for the overtime record.
void onSignUp(Integer overtimeId) {
// check to see if the OT has been deleted or modified or signed-up
Overtime ot = (Overtime)appService.getById(Overtime.class, overtimeId);
if (ot == null) {
visit.setOneTimeMessage("The overtime has already been deleted.");
return;
}
if (ot.getStatus() != null && ot.getStatus() != AppConst.OT_NEW) {
visit.setOneTimeMessage("The overtime has already been signed up. Please choose a different one to sign up.");
return;
}
...
try {
appService.validateOvertimeForUser(agency, user, ot);
appService.handleSignUpOvertime(agency, user, ot);
// log activity
String what = "Signed up for overtime " + ot.getRefNo() + ".";
appService.logActivity(user, AppConst.LOG_OVERTIME, what);
} catch(HibernateOptimisticLockingFailureException x) {
visit.setOneTimeMessage("The overtime record has been changed by another user, please try again.");
return;
} catch(Exception e) {
visit.setOneTimeMessage(e.getMessage());
return;
}
...

TomEE and MySql - query don't returns any results

I am using TomeEE + MySql and i have problem because function createNamedQuery don't returns any results. I thought that problem is with my
entityManager but i checked in debugMode and is injected.
This is my code:
User Entity:
package pl.gsite.db.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "user")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "User.loginAndPassword", query = "SELECT u FROM User u WHERE u.login = :login and u.password = :password"),
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByLogin", query = "SELECT u FROM User u WHERE u.login = :login"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password")})
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "id")
private Integer id;
#Size(max = 100)
#Column(name = "login")
private String login;
#Size(max = 100)
#Column(name = "password")
private String password;
public User() {
}
public User(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "pl.gsite.db.model.User[ id=" + id + " ]";
}
}
My ManagedBean:
package pl.gsite.bean.request;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateful;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Context;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import pl.gsite.bean.session.LoggedUserBean;
import pl.gsite.db.model.User;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
#Named(value = "loginRequest")
#RequestScoped
public class LoginRequest {
#PersistenceContext(unitName = "gsitePU")
private EntityManager em;
#Inject
private LoggedUserBean loggedUserBean;
private String login;
private String password;
public LoginRequest() {
}
public String authentication() {
try {
List<User> uList = new ArrayList<User>();
TypedQuery qq = em.createNamedQuery("User.findAll", User.class);
uList = qq.getResultList(); // <-- returns empty list
TypedQuery<User> query = em.createNamedQuery("User.loginAndPassword", User.class).setParameter("login", login).setParameter("password", password);
User u = query.getSingleResult(); // <-- throws an NoResultException
this.loggedUserBean.setLoggedUser(u);
}
catch(NoResultException e) {
e.printStackTrace();
}
return "index";
}
/**
* #return the login
*/
public String getLogin() {
return login;
}
/**
* #param login the login to set
*/
public void setLogin(String login) {
this.login = login;
}
/**
* #return the password
*/
public String getPassword() {
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
persistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="gsitePU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>gsite_mysql</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(foreignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
I had the same issue. I changed the jpa persistence from openJPA to eclipseLink. The problem resolved.

Why CreateEntityManager returns NULL

I am new to java technology so please excuse me if I present a silly problem...
I want to make a JSF 2.0 servlet and use MySql for database engine.
The problem is that it's seems that I can't connect to server.
I use netbeans IDE, and for guide I use a tutorial from youtube: http://www.youtube.com/watch?v=UBNaiVWwAZw&feature=related
The difference is that I use Tomcat.
My persistence.xml file is in Web/META-INF/persistence.xml and the content is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="AnunturiJsfPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>my.servlets.Users</class>
<class>my.servlets.UsersSessions</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/tz_cadastru_galati"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
</persistence>
my servlet file is:
package my.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "testOkServlet2", urlPatterns = {"/testOkServlet2"})
public class testOkServlet2 extends HttpServlet {
#PersistenceUnit
EntityManagerFactory emf;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
EntityManager em = emf.createEntityManager();
Users u = (Users) em.createNamedQuery("Users.findAll").getResultList().get(0);
String myUser = u.getUserNume();
out.println("User:" + myUser);
} catch (Exception e)
{
out.println(e.getMessage());
}
finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
and this is my Users object:
package my.servlets;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findByUserID", query = "SELECT u FROM Users u WHERE u.userID = :userID"),
#NamedQuery(name = "Users.findByUserNume", query = "SELECT u FROM Users u WHERE u.userNume = :userNume"),
#NamedQuery(name = "Users.findByNumePrenume", query = "SELECT u FROM Users u WHERE u.numePrenume = :numePrenume"),
#NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email"),
#NamedQuery(name = "Users.findByParola", query = "SELECT u FROM Users u WHERE u.parola = :parola"),
#NamedQuery(name = "Users.findByContActiv", query = "SELECT u FROM Users u WHERE u.contActiv = :contActiv"),
#NamedQuery(name = "Users.findByDataAdaugarii", query = "SELECT u FROM Users u WHERE u.dataAdaugarii = :dataAdaugarii"),
#NamedQuery(name = "Users.findByNivelAccesID", query = "SELECT u FROM Users u WHERE u.nivelAccesID = :nivelAccesID")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "userID")
private Integer userID;
#Basic(optional = false)
#Column(name = "userNume")
private String userNume;
#Basic(optional = false)
#Column(name = "numePrenume")
private String numePrenume;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Basic(optional = false)
#Column(name = "parola")
private String parola;
#Basic(optional = false)
#Column(name = "contActiv")
private boolean contActiv;
#Basic(optional = false)
#Column(name = "dataAdaugarii")
#Temporal(TemporalType.TIMESTAMP)
private Date dataAdaugarii;
#Basic(optional = false)
#Column(name = "nivelAccesID")
private short nivelAccesID;
public Users() {
}
public Users(Integer userID) {
this.userID = userID;
}
public Users(Integer userID, String userNume, String numePrenume, String email, String parola, boolean contActiv, Date dataAdaugarii, short nivelAccesID) {
this.userID = userID;
this.userNume = userNume;
this.numePrenume = numePrenume;
this.email = email;
this.parola = parola;
this.contActiv = contActiv;
this.dataAdaugarii = dataAdaugarii;
this.nivelAccesID = nivelAccesID;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
public String getUserNume() {
return userNume;
}
public void setUserNume(String userNume) {
this.userNume = userNume;
}
public String getNumePrenume() {
return numePrenume;
}
public void setNumePrenume(String numePrenume) {
this.numePrenume = numePrenume;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getParola() {
return parola;
}
public void setParola(String parola) {
this.parola = parola;
}
public boolean getContActiv() {
return contActiv;
}
public void setContActiv(boolean contActiv) {
this.contActiv = contActiv;
}
public Date getDataAdaugarii() {
return dataAdaugarii;
}
public void setDataAdaugarii(Date dataAdaugarii) {
this.dataAdaugarii = dataAdaugarii;
}
public short getNivelAccesID() {
return nivelAccesID;
}
public void setNivelAccesID(short nivelAccesID) {
this.nivelAccesID = nivelAccesID;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userID != null ? userID.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Users)) {
return false;
}
Users other = (Users) object;
if ((this.userID == null && other.userID != null) || (this.userID != null && !this.userID.equals(other.userID))) {
return false;
}
return true;
}
#Override
public String toString() {
return "my.servlets.Users[ userID=" + userID + " ]";
}
}
If I missed to post any other information please tell me and I will put it online.
Please help me.
Manny thanks in advance.
First thing to to in a situation like this is to check the connection to server manually to make sure that you have access to server.