关键代码:
session.get():立即加载。
session.load():延迟加载、懒加载
代码片段:
package com.shuoeasy.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * Unit test for simple App. */ public class AppTest { Session session; SessionFactory sf; @Before public void init() { Configuration conf = new Configuration().configure(); ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build(); sf = conf.buildSessionFactory((org.hibernate.service.ServiceRegistry) sr); session = sf.openSession(); session.beginTransaction(); System.out.println("init"); } @After public void destory() { session.getTransaction().commit(); session.close(); sf.close(); System.out.println("dectory"); } /** * save之前是个零时的持久化对象 * save后得到数据库的id */ @Test public void testSave1(){ News news = new News("标题","内容"); System.out.println(news); // News [id=0, title=标题, content=内容] session.save(news); System.out.println(news); //id有值了 News [id=29, title=标题, content=内容] } /** * 不允许设置id,如果设置了也是无效的 */ @Test public void testSave2(){ News news = new News("标题","内容"); news.setId(123); // 无效代码 session.save(news); } /** * 不允许更新id */ @Test public void testSave3(){ News news = (News) session.get(News.class, 1); news.setId(123); // 无效代码 session.save(news); } /** * 如果有id,就不插入数据 */ @Test public void testPersist(){ News news = new News("标题","内容"); news.setId(123); session.persist(news); // 有id了,不插入数据 } /** * 1.延迟加载,若不调用该对象,则不会立即执行查询操作,而是返回代理对象 * 2.如果数据库中没有对应的数据,则会抛异常 */ @Test public void testLoad(){ News news = (News) session.load(News.class, 1); System.out.println(news); // 注释掉此行,将不会对数据库进行查询 } /** * 懒加载异常 LazyInitializationException * 需要代理对象之前,关闭了session,这时候会报错 */ @Test public void testLoad2(){ News news = (News) session.load(News.class, 1); session.close(); // 懒加载异常 LazyInitializationException System.out.println(news); // 注释掉此行,将不会对数据库进行查询 } }