package com.cv.hibernate.version;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import com.cv.hibernate.version.model.EmployeeBean;
import com.cv.hibernate.version.util.HibernateUtil;
/**
* @author Chandra Vardhan
*/
public class TestClient {
/**
* @param args
*/
private final static Logger logger = Logger.getLogger(TestClient.class);
public static void main(String[] args) {
long id = saveOrUpdate();
Session sessionTwo = HibernateUtil.getSession();
sessionTwo.beginTransaction();
EmployeeBean eb = (EmployeeBean) sessionTwo.load(EmployeeBean.class, new Long(id));
logger.info("loaded object from the database is :");
logger.info(eb.getId() + " " + eb.getFirstName() + " " + eb.getLastName() + " " + eb.getEmail() + " "
+ eb.getVersion());
eb.setFirstName("chote");
sessionTwo.update(eb);
logger.info(eb.getId() + " " + eb.getFirstName() + " " + eb.getLastName() + " " + eb.getEmail() + " "
+ eb.getVersion());
sessionTwo.getTransaction().commit();
sessionTwo.close();
Session sessionThree = HibernateUtil.getSession();
sessionThree.beginTransaction();
logger.info("After first update :");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
EmployeeBean eb1 = (EmployeeBean) sessionThree.load(EmployeeBean.class, new Long(id));
logger.info(eb1);
eb1.setLastName("netha");
sessionThree.update(eb1);
sessionThree.getTransaction().commit();
logger.info("After second update :");
logger.info(eb1.getId() + " " + eb1.getFirstName() + " " + eb1.getLastName() + " " + eb1.getEmail() + " "
+ eb1.getVersion());
HibernateUtil.closeSession();
}
public static long saveOrUpdate() {
Session session = HibernateUtil.getSession();
session.beginTransaction();
Query query = session.createQuery("select max(eb1.id) from EmployeeBean as eb1");
List list = query.list();
long maxId = 0;
if (list != null && !list.isEmpty()) {
Object object = list.get(0);
if (object != null) {
maxId = (Long) object;
}
}
maxId = maxId + 1;
EmployeeBean emp = new EmployeeBean();
emp.setId(new Long(maxId));
emp.setFirstName("chandra");
emp.setLastName("vardhan");
emp.setEmail("meetkodam@gmail.com");
session.saveOrUpdate(emp);
logger.info("Saved successful...");
session.getTransaction().commit();
logger.info(emp.getId() + " " + emp.getFirstName() + " " + emp.getLastName() + " " + emp.getEmail() + " "
+ emp.getVersion());
logger.info("First time saved to the database...");
session.close();
return maxId;
}
} |
No comments:
Post a Comment