[英]Hibernate 4 -> 5 upgrade leads to LazyInitializationException
我将项目从Spring 4.3.9.RELEASE + Hibernate 4.3.11.Final升级到了Spring Boot 2.1.4.RELEASE和Hibernate 5.3.9.Final。 查询仍然可以正常工作,但是我收到了带有@OneToMany
类成员的LazyInitializationException
。
首先,我从@Transaction
服务检索该对象,该对象具有对@OneToMany
列表的引用。 集合返回到控制器,然后从那里回到Spring序列化为json。 控制器具有@RestController
,因此它知道该怎么做。
在Spring 4.3.9.RELEASE + Hibernate 4.3.11.Final中,一切都很好,即使未通过配置启用OpenEntityManagerInView
并且未使用EAGER模式加载集合。 但是在Spring Boot 2.1.4.RELEASE和Hibernate 5.3.9.Final中,相同的东西不再起作用。 我已经尝试通过设置spring.jpa.open-in-view=true
启用OEMIV,但即使这样似乎也不起作用或被某个地方覆盖。
如果我为该集合启用EAGER加载模式,则一切正常。
的pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
@Entity
@JsonSerialize(using = TemplateSerializer.class)
public class Template implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToOne
private ObjFormat objFormat;
@OneToOne
@JoinColumn(name = "event_id")
@OnDelete(action = OnDeleteAction.CASCADE)
private Event event;
@OneToMany
@JoinColumn(name = "category_id")
private List<Category> linkToCategories;
该问题是由字段linkToCategories引起的。 如果我配置@OneToMany(fetch = FetchType.EAGER),一切正常。
应用配置:
@Bean
public LocalSessionFactoryBean sessionFactory(DataSource dataSource) throws ClassNotFoundException {
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(dataSource);
localSessionFactoryBean.setPackagesToScan("com.project.backend.model",
"com.project.backend.hibernate.converters");
return localSessionFactoryBean;
}
@Bean
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
return new HibernateTransactionManager(sessionFactory);
}
以后的编辑:经过大量调试,新旧Hibernate功能之间的区别在于HibernateTransactionManager。 在方法doGetTransaction()中,在Hibernate 4中,它在调用时找到SessionHolder对象
TransactionSynchronizationManager.getResource(了getSessionFactory())
而在Hibernate 5中则没有。
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory()); if (sessionHolder != null) { if (logger.isDebugEnabled()) { logger.debug("Found thread-bound Session [" + sessionHolder.getSession() + "] for Hibernate transaction"); } txObject.setSessionHolder(sessionHolder); } else if (this.hibernateManagedSession) { try { Session session = this.sessionFactory.getCurrentSession(); if (logger.isDebugEnabled()) { logger.debug("Found Hibernate-managed Session [" + session + "] for Spring-managed transaction"); } txObject.setExistingSession(session); } catch (HibernateException ex) { throw new DataAccessResourceFailureException( "Could not obtain Hibernate-managed Session for Spring-managed transaction", ex); } }
在doBegin方法中,将创建一个新会话,并在每个请求的txObject上进行设置。
if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
Interceptor entityInterceptor = getEntityInterceptor();
Session newSession = (entityInterceptor != null ?
getSessionFactory().withOptions().interceptor(entityInterceptor).openSession() :
getSessionFactory().openSession());
if (logger.isDebugEnabled()) {
logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction");
}
txObject.setSession(newSession);
}
我在Hibernate方面的经验非常少,因此我陷入了困境。 可能是配置问题,但我找不到。
正如M.Deinum所说的那样,Spring 4.3.9.RELEASE + Hibernate 4.3.11.Final配置正在加载OpenSessionInViewFilter,这解释了为什么所有查询都成功进行的原因。 在Spring Boot中配置相同的过滤器后,一切恢复正常。 添加以下bean以注册过滤器:
@Bean
public FilterRegistrationBean<OpenSessionInViewFilter> registerOpenSessionInViewFilterBean() {
FilterRegistrationBean<OpenSessionInViewFilter> registrationBean = new FilterRegistrationBean<>();
OpenSessionInViewFilter filter = new OpenSessionInViewFilter();
registrationBean.setFilter(filter);
return registrationBean;
}
下一步是将纯Hibernate替换为JPA,将OpenSessionInViewFilter替换为OpenEntityManagerInViewFilter。
谢谢M. Deinum。
@xxxToMany
注释指示默认情况下,访存类型为LAZY
。 这意味着您需要初始化实体引用的集合。
例如。
@Entity
public class Book {
@OneToMany
public List<Author> authors;
}
解决此问题的方法很少。 您可以使用以下命令修改@OneToMany
批注:
@OneToMany(FetcType=FetchType.EAGER)
或制作一个方法来初始化authors
例如:
public void initializeAuthors(Book book) {
Book b = em.find(Book.class, book.getId());
List<Author> authors = new ArrayList<>(b.getAuthors());
book.setAuthors(authors);
}
如果您的实体上有@NamedQueries
,则可以通过在集合上添加LEFT JOIN FETCH
来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.