1 package cn.lonecloud.test.crud; 2 3 import org.hibernate.HibernateException; 4 import org.hibernate.Session; 5 import org.hibernate.SessionFactory; 6 import org.hibernate.Transaction; 7 import org.hibernate.cfg.Configuration; 8 import org.junit.Before; 9 import org.junit.Test; 10 11 import cn.lonecloud.domain.Customer; 12 13 public class GetAndLoad { 14 15 private Session session; 16 17 private SessionFactory buildSessionFactory; 18 19 public SessionFactory getBuildSessionFactory() { 20 return buildSessionFactory; 21 } 22 23 public void setBuildSessionFactory(SessionFactory buildSessionFactory) { 24 this.buildSessionFactory = buildSessionFactory; 25 } 26 27 public void setSession(Session session) { 28 this.session = session; 29 } 30 31 @Before 32 public void getSession() { 33 Configuration cfg = new Configuration().configure(); 34 setBuildSessionFactory(cfg.buildSessionFactory()); 35 session= buildSessionFactory.openSession(); 36 } 37 @Test 38 public void getTest(){ 39 Transaction transaction = null; 40 try { 41 transaction = session.beginTransaction();//创建session 42 //get默认为非懒加载模式进行的不管设置设置懒加载 43 //get方法首先查询session缓存,没有的话查询二级缓存,最后查询数据库; 44 //反而load方法创建时首先查询session缓存,没有就创建代理,实际使用数据时才查询二级缓存和数据库。 45 Customer customer = (Customer) session.get(Customer.class, "2c90ab8157cda51a0157cda51b330000"); 46 System.out.println(customer.getId()); 47 customer.getOrders(); 48 transaction.commit();//提交事务 49 } catch (HibernateException e) { 50 if (transaction!=null) { 51 transaction.rollback();//事务回滚 52 } 53 e.printStackTrace(); 54 }finally{ 55 if (session!=null&&session.isOpen()) { 56 session.close();//关闭session 57 } 58 } 59 } 60 @Test 61 public void loadTest(){ 62 Transaction transaction = null; 63 try { 64 transaction = session.beginTransaction();//创建session 65 //get默认为非懒加载模式进行的不管设置设置懒加载 66 //get方法首先查询session缓存,没有的话查询二级缓存,最后查询数据库; 67 //反而load方法创建时首先查询session缓存,没有就创建代理,实际使用数据时才查询二级缓存和数据库。 68 Customer customer = (Customer) session.load(Customer.class, "2c90ab8157cda51a0157cda51b330000"); 69 System.out.println(customer.getId()); 70 customer.getOrders(); 71 transaction.commit();//提交事务 72 } catch (HibernateException e) { 73 if (transaction!=null) { 74 transaction.rollback();//事务回滚 75 } 76 e.printStackTrace(); 77 }finally{ 78 if (session!=null&&session.isOpen()) { 79 session.close();//关闭session 80 } 81 } 82 } 83 }
//get默认为非懒加载模式进行的不管设置设置懒加载
//get方法首先查询session缓存,没有的话查询二级缓存,最后查询数据库;
//反而load方法创建时首先查询session缓存,没有就创建代理,实际使用数据时才查询二级缓存和数据库。
具体:
http://blog.csdn.net/javaloveiphone/article/details/8184941