package cn.lonecloud.test.crud; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Before;
import org.junit.Test; import cn.lonecloud.domain.Customer; public class GetAndLoad { private Session session; private SessionFactory buildSessionFactory; public SessionFactory getBuildSessionFactory() {
return buildSessionFactory;
} public void setBuildSessionFactory(SessionFactory buildSessionFactory) {
this.buildSessionFactory = buildSessionFactory;
} public void setSession(Session session) {
this.session = session;
} @Before
public void getSession() {
Configuration cfg = new Configuration().configure();
setBuildSessionFactory(cfg.buildSessionFactory());
session= buildSessionFactory.openSession();
}
@Test
public void getTest(){
Transaction transaction = null;
try {
transaction = session.beginTransaction();//创建session
//get默认为非懒加载模式进行的不管设置设置懒加载
//get方法首先查询session缓存,没有的话查询二级缓存,最后查询数据库;
//反而load方法创建时首先查询session缓存,没有就创建代理,实际使用数据时才查询二级缓存和数据库。
Customer customer = (Customer) session.get(Customer.class, "2c90ab8157cda51a0157cda51b330000");
System.out.println(customer.getId());
customer.getOrders();
transaction.commit();//提交事务
} catch (HibernateException e) {
if (transaction!=null) {
transaction.rollback();//事务回滚
}
e.printStackTrace();
}finally{
if (session!=null&&session.isOpen()) {
session.close();//关闭session
}
}
}
@Test
public void loadTest(){
Transaction transaction = null;
try {
transaction = session.beginTransaction();//创建session
//get默认为非懒加载模式进行的不管设置设置懒加载
//get方法首先查询session缓存,没有的话查询二级缓存,最后查询数据库;
//反而load方法创建时首先查询session缓存,没有就创建代理,实际使用数据时才查询二级缓存和数据库。
Customer customer = (Customer) session.load(Customer.class, "2c90ab8157cda51a0157cda51b330000");
System.out.println(customer.getId());
customer.getOrders();
transaction.commit();//提交事务
} catch (HibernateException e) {
if (transaction!=null) {
transaction.rollback();//事务回滚
}
e.printStackTrace();
}finally{
if (session!=null&&session.isOpen()) {
session.close();//关闭session
}
}
}
}
//get默认为非懒加载模式进行的不管设置设置懒加载
//get方法首先查询session缓存,没有的话查询二级缓存,最后查询数据库;
//反而load方法创建时首先查询session缓存,没有就创建代理,实际使用数据时才查询二级缓存和数据库。
具体:
http://blog.csdn.net/javaloveiphone/article/details/8184941