在带有 jpa/hibernate 的 Spring 中,如何保持会话打开以避免延迟初始化异常? [英] In Spring with jpa/hibernate, how do I keep a session open to avoid lazy initialization exceptions?

查看:34
本文介绍了在带有 jpa/hibernate 的 Spring 中,如何保持会话打开以避免延迟初始化异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前将实体 bean 中的集合标记为渴望避免在使用 EntityManager 加载 bean 后尝试访问集合属性时出现延迟初始化异常.

I currently mark collections in entity beans as eager to avoid getting a lazy initialization exception when I try to access the collection properties after loading the bean with the EntityManager.

如果我将集合保留为延迟加载,我如何保持会话打开?我想尝试使用@Transactional,但即使有效,我也不想这样做,因为在很长的方法中打开事务似乎是不正确的.

If I instead leave the collection as lazy loading, how do I keep a session open? I thought about trying @Transactional, but even if that worked I wouldn't want to do it because it doesn't seem right to leave a transaction open over a long method.

推荐答案

https://www.hibernate.org/43.html

基本上,您有几个选择.

Basically, you have a few options.

-您可以使用在视图中打开会话"模式,其中使用过滤器/拦截器/AOP 样式逻辑在服务器端逻辑开始时打开会话,并在会话结束时关闭它.

-You can use the "open session in view" pattern where you use a filter/interceptor/AOP - style logic to open a session when server side logic begins, and close it when it's through.

-您可以实现跨越多个请求-响应周期的对话.

-You could implement conversations spanning several request-response cycles.

一个普通的老式 Servlet 过滤器是最简单的.

A plain old Servlet Filter is the easiest.

这篇关于在带有 jpa/hibernate 的 Spring 中,如何保持会话打开以避免延迟初始化异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆