我在 JBoss AS 7.1.1 上有一个 EJB 应用程序,它使用 Hibernate 4.3 通过 jta-data-source 进行数据库连接。我的 persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/postds</jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.ProgressDialect" />
<property name="hibernate.connection.charSet" value="UTF-8" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
我使用 DAO 模式,如 this :
@Stateless
public abstract class GenericHibernateDAO<T, ID extends Serializable>
implements GenericDAO<T, ID> {
private Class<T> persistentClass;
@PersistenceContext
private EntityManager em;
protected Session getSession() {
return em.unwrap(Session.class);
}
public T save(T entity) {
getSession().saveOrUpdate(entity);
return entity;
}
...
在 EJB 后端中,所有延迟初始化字段都可以正常工作。现在我的后端需要一个小型网络管理面板。我熟悉 Spring MVC 并决定使用它。在 Spring MVC 中使用 EJB beans 不是问题。但是延迟初始化字段在 Spring Controller 中不起作用,我得到:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
我尝试在 web.xml 中使用 OpenSessionInViewFilter:
<filter>
<filter-name>openSessionFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSessionFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
OpenSessionInViewFilter 需要 sessionFactory bean。我将其定义添加到 applicationContext.xml 中:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd">
<jee:jndi-lookup id="dataSource" jndi-name="java:/postds"/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
但这并没有解决我的问题...你有什么建议吗? 非常感谢!
最佳答案
如果您使用 EJB,容器会为您管理事务和 session 。事务提交后(默认情况下所有 EJB 方法都是事务性的)容器销毁 session 。如果您使用延迟加载,则会收到 org.hibernate.LazyInitializationException 异常。
尝试通过 HQL 或 Criteria API 使用 fetch join 延迟加载字段。
请参阅this answer了解更多信息。
关于java - Spring MVC 前端和 EJB 后端中的 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21912156/