Hibernate clear()方法的解释以及用法 load()方法懒加载问题

 

1、clear()

  无论是Load 还是 Get 都会首先查找缓存(一级缓存) 如果没有,才会去数据库查找,调用Clear() 方法,可以强制清除Session缓存

 

package com.zking.entity;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zking.uitl.SessionFactoryUtils;

public class MyText {
	Session session = SessionFactoryUtils.openSession();
	Transaction transaction = session.beginTransaction();

	@Test
	public void select() {
		Login l = session.get(Login.class, "2018-09-05-19-56-57");
		System.out.println(l);
		System.out.println(session);
		session.clear();
		System.out.println(l);
		System.out.println(session);
	}

}

 下面是我的控制台输出结果

ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
Hibernate: 
    select
        login0_.ID as ID1_0_0_,
        login0_.NAME as NAME2_0_0_,
        login0_.PASSWORD as PASSWORD3_0_0_,
        login0_.SEX as SEX4_0_0_ 
    from
        login login0_ 
    where
        login0_.ID=?
Login [id=2018-09-05-19-56-57, name=发放, password=烦烦烦, sex=男]
SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.zking.entity.Login#2018-09-05-19-56-57]],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])
Login [id=2018-09-05-19-56-57, name=发放, password=烦烦烦, sex=男]
SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=ExecutableList{size=0} updates=ExecutableList{size=0} deletions=ExecutableList{size=0} orphanRemovals=ExecutableList{size=0} collectionCreations=ExecutableList{size=0} collectionRemovals=ExecutableList{size=0} collectionUpdates=ExecutableList{size=0} collectionQueuedOps=ExecutableList{size=0} unresolvedInsertDependencies=null])

clear()执行之前session是有值的 ,执行之后便会所有对象都会被清空,第二个会输出值则是因为get()是一个及时加载的方法,它会获取到之前的值

2、load()

    1.>延迟加载:不会立即调用sql语句,只有用的时候才调用

这是load()

这是get()

   对比一下就知道了,load()并不会及时加载

     2.>若数据库中没有相对应的值,则会报错(这个就不说了,报错很明显的)

 

     3.>关闭session之后会出现懒加载问题

这个问题也很好解决,在你映射的实体类的<class>中加上lazy="false"(不使用懒加载)  属性即可

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值