- 延迟加载
1. 延迟加载先获取到代理对象,当真正使用到该对象中的属性的时候,才会发送SQL语句,是Hibernate框架提升性能的方式
2. 类级别的延迟加载
* Session对象的load方法默认就是延迟加载
* Customer c = session.load(Customer.class, 1L);没有发送SQL语句,当使用该对象 的属性时,才发送SQL语句
* 使类级别的延迟加载失效
* 在对象映射文件中<class>标签上配置lazy=”false”
* Hibernate.initialize(Object proxy);
/** * 演示类级别的延迟加载 * 需要使用session.load()方法 ,它默认情况下使用延迟加载 */ @Test public void run1() { //先做一个比较啊 Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); Customer customer = session.get(Customer.class, 1L); System.out.println("==============================="); System.out.println(customer.getCust_name()); tx.commit(); } /** * 使用延迟加载 */ @Test public void run2() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); Customer customer = session.load(Customer.class, 1L); System.out.println("==============================="); System.out.println(customer.getCust_name()); tx.commit(); }/** * 将延迟加载失效的方式 * 在<class>标签上配置lazy=”false” * Hibernate.initialize(Object proxy); */ @Test public void run3() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); Customer customer = session.load(Customer.class, 1L); //把customer对象初始化 Hibernate.initialize(customer); System.out.println("==============================="); System.out.println(customer.getCust_name()); tx.commit(); }
3.关联级别的延迟加载
/** * 关联级别的延迟加载 * 查询某个客户,当查询某个客户下的联系人是否延迟加载 * 默认情况下延迟加载 */ @Test public void run4() { Session session = HibernateUtils.getCurrentSession(); Transaction tx = session.beginTransaction(); Customer customer = session.get(Customer.class, 1L); System.out.println("============================"); System.out.println(customer.getLinkmans().size()); tx.commit(); }
时间: 2024-10-20 06:53:23