failed to lazily initialize a collection of role,解决Hibernate查询报错

news/2024/7/7 20:41:36 标签: pycharm, ide, python

Hibernate报错:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.jiuqi.gov.common.attatchment.entity.AttachmentEntity.properties, could not initialize proxy - no Session
        at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:614) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:162) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at org.hibernate.collection.internal.PersistentMap.size(PersistentMap.java:148) ~[hibernate-core-5.6.9.Final.jar:5.6.9.Final]
        at java.util.HashMap.putMapEntries(HashMap.java:502) ~[?:1.8.0_381]
        at java.util.HashMap.<init>(HashMap.java:491) ~[?:1.8.0_381]
        at com.jiuqi.gov.common.attatchment.entity.AttachmentEntity.toAttachmentInfo(AttachmentEntity.java:293) ~[common.attachment-1.5.1.jar:?]

原代码:

public List<AttachmentInfo> getAttachmentById(UUID id){
		String table = "com.fdw.AttachmentEntity";
		List<AttachmentInfo> result = new ArrayList<>();
		List<AttachmentEntity> resultList = template.execute(new HibernateCallback<List<AttachmentEntity>>() {
			@Override
			public List<AttachmentEntity> doInHibernate(Session session) throws HibernateException {
				String sql = "from " + table + " where Id = :id";
				Query<AttachmentEntity> query = session.createQuery(sql, AttachmentEntity.class);
				query.setParameter("id", id);
				return query.getResultList();
			}
		});
		for (AttachmentEntity attachmentEntity : resultList){
			result.add(attachmentEntity.toAttachmentInfo());
		}
		return result;
	}

问题原因:

 AttachmentEntity 类有个懒加载的字段 properties,关联了其他表。

关于懒加载

所谓懒加载(lazy)就是延时加载,延迟加载。即不是不加载,而是在需要的时候才加载。

什么时候用懒加载呢,我只能回答要用懒加载的时候就用懒加载。

至于为什么要用懒加载呢,就是当我们要访问的数据量过大时,明显用缓存不太合适,

因为内存容量有限 ,为了减少并发量,减少系统资源的消耗,

我们让数据在需要的时候才进行加载,这时我们就用到了懒加载。

比如部门ENTITY和员工ENTITY,部门与员工1对多,

如果lazy设置为 false,那么只要加载了一个部门的po,就会根据一对多配置的关系把所有员工的po也加载出来。

但是实际上有时候只是需要用到部门的信息,不需要用到 员工的信息,这时员工po的加载就等于浪费资源。如果lazy设置为true,那么只有当你访问部门po的员工信息时候才回去加载员工的po的信息。

hibernate3.0 中 lazy有三个值:

lazy有三个属性:true、false、extra

【true】:默认取值,它的意思是只有在调用这个集合获取里面的元素对象时,才发出查询语句,加载其集合元素的数据 。即只有在使用的时候才发出查询命令。

【false】:取消懒加载特性,即在加载对象的同时,就发出第二条查询语句加载其关联集合的数据即加载对象的时候就发出查询语句,加载关联的子类数据。


【extra】:一种比较聪明的懒加载策略,即调用集合的size/contains等方法的时候,hibernate并不会去加载整个集合的数据,而是发出一条聪明的SQL语句,以便获得需要的值,只有在真正需要用到这些集合元素对象数据的时候,才去发出查询语句加载所有对象的数据

 

 

解决后代码:

public List<AttachmentInfo> getAttachmentById(UUID id){
		String table = "com.fdw.AttachmentEntity";
		List<AttachmentInfo> result = new ArrayList<>();
		template.execute(new HibernateCallback<List<AttachmentEntity>>() {
			@Override
			public List<AttachmentEntity> doInHibernate(Session session) throws HibernateException {
				String sql = "from " + table + " where Id = :id";
				Query<AttachmentEntity> query = session.createQuery(sql, AttachmentEntity.class);
				query.setParameter("id", id);
				List<AttachmentEntity> resultList = query.getResultList();
				for (AttachmentEntity attachmentEntity : resultList){
					result.add(attachmentEntity.toAttachmentInfo());
				}
				return null;
			}
		});
		return result;
	}


http://www.niftyadmin.cn/n/5535302.html

相关文章

Entity Framework EF Migration 迁移

针对Code First来说关注的只有实体类。当需求变更时只需要添加新的实体类或者在实体类中添加、删除、修改属性即可。但是修改完成之后要如何将修改同步到数据库中&#xff1f; migration 机制就出现了 ●启用Migrations   ●通过Add-Migration添加Migration   ●Update-D…

Nettyの网络聊天室扩展序列化算法

1、网络聊天室综合案例 客户端初始代码&#xff1a; Slf4j public class ChatClient {public static void main(String[] args) {NioEventLoopGroup group new NioEventLoopGroup();LoggingHandler LOGGING_HANDLER new LoggingHandler(LogLevel.DEBUG);MessageCodecSharabl…

C++中的类型转换操作符:static_cast reinterpret_cast const_cast dynamic_cast

目录​​​​​​​ C语言中的类型转换 C中的类型转换 C中的类型转换操作符 static_cast reinterpret_cast const_cast volatile关键字 赋值兼容 dynamic_cast C语言中的类型转换 基本概念&#xff1a;赋值运算符左右两侧类型不同&#xff0c;或形参与实参类型不匹配…

FastAPI-Cookie

fastapi-learning-notes/codes/ch01/main.py at master Relph1119/fastapi-learning-notes GitHub 1、Cookie的作用 Cookie可以充当用户认证的令牌&#xff0c;使得用户在首次登录后无需每次手动输入用户名和密码&#xff0c;即可访问受限资源&#xff0c;直到Cookie过期或…

设计模式-结构型-08-组合模式

文章目录 1、学校院系展示需求2、组合模式基本介绍3、组合模式示例3.1、 解决学校院系展示&#xff08;透明模式1&#xff09;3.2、高考的科目&#xff08;透明模式2&#xff09;3.3、高考的科目&#xff08;安全组合模式&#xff09; 4、JDK 源码分析5、注意事项和细节 1、学校…

BUG:AttributeError: module ‘websocket‘ has no attribute ‘enableTrace’

AttributeError: module ‘websocket’ has no attribute enableTrace’ 环境 windows 11 Python 3.10websocket 0.2.1 websocket-client 1.8.0 websockets 11.0.3 rel 0.4.9.19详情 一开始…

PromptCraft-Robotics部署步骤和问题记录

GitHub - microsoft/PromptCraft-Robotics: Community for applying LLMs to robotics and a robot simulator with ChatGPT integration 部署环境&#xff1a;UE4.27 Visual Studio 2022 Arisim1.8.1 可参考&#xff1a;git clone https://github.com/Microsoft/AirSim.gi…

保函到期提醒是银行或金融机构提供的一项服务,旨在确保客户及时了解保函即将到期的情况,从而避免因保函过期而导致的风险或违约责任。

保函到期提醒是银行或金融机构提供的一项服务&#xff0c;旨在确保客户及时了解保函即将到期的情况&#xff0c;从而避免因保函过期而导致的风险或违约责任。以下是保函到期提醒的一些关键方面&#xff1a; 1. **保函定义**&#xff1a; - 保函是一种由银行出具的书面承诺&…