您的位置:首页 > 大数据 > 人工智能

Hibernate的加载抓取方式:Failed to lazily initialize a collection - no session

2015-11-06 01:31 531 查看
hibernate与数据库之间通过session交互[1]

hibernate在处理1对多的业务时很可能会出现标题所列错误.

例如

user和office是1对多

Office office = task.getOffice();

List<User> userList = office.getUserList(); //这句导致报告懒初始化集合失败

失败的原因, 目前看到是因为没有找到Hibernate交互用的会话.而会话为什么没出现?

是因为没人去建?

1 懒抓取,所以只需要找找内存

2 未在spring中创建会话

修改方法就是

1 将懒改成勤快eager

2 在spring中提供session

说道懒和勤快.Hibernate之所以喜欢懒,是因为这样的抓取,所获得的数据都在内存中(或内存实体中,例如Office这个实体里)

而勤快,意味着无实体的一次次实际sql操作.因而在频繁使用的场合,勤快会导致性能下降.

参考:

1 http://stackoverflow.com/questions/3519059/hibernate-failed-to-lazily-initialize-a-collection-of-role-no-session-or-sessi

摘录内容

If you have a large collection, you shouldn't use eager fetching. It jointly selects all data mapped to your entry and loads to memory. An alternative to this is to still use lazy fetching and open a Hibernate session each time you need to work on the related
collection, i.e, each time you need to invoke getRoleSet method. This way, Hibernate will execute the select query to database each time this method is invoked and doesn't keep the collection data in memory. You can refer to my post here for details: http://khuevu.github.io/2013/01/20/understand-hibernate.html

That's said, it can depend on your actual use case. If your collection data is small and you frequently need to query the data, you will better off using eager fetching. I think, in your specific case, a collection of role is probably quite small and suitable
to use eager fetching.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: