gpt4 book ai didi

hibernate - OpenEntityManagerInViewFilter 问题

转载 作者:行者123 更新时间:2023-12-02 23:16:41 25 4
gpt4 key购买 nike

我已经在这个网站和其他网站上搜索过让 OpenEntityManagerInViewFilter 工作的答案。我有一个标准的 User 对象,它引用具有多对多关系的角色对象作为一个集合。当我尝试从 Controller 编辑我的用户时,我收到了可怕的延迟初始化异常。在大多数情况下,通过简单地将其添加到您的 web.xml 中,这似乎应该是非常简单的:

<filter>
<filter-name>oemInViewFilter</filter-name>
<filter-class>
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>oemInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

现在我尝试过但没有成功的事情(这些是来自网络的各种建议)

  1. 将上述声明移至 web.xml 的最顶部
  2. 在我的 Controller 方法和/或整个类周围使用@Transactional
  3. 显然将获取类型切换为 Eager Works,但这里违背了我的意图
  4. 使用我定义的entityManagerFacorty
  5. 已验证 OpenEntityManager 存在于惰性初始化异常中,因此它被触发

我读过的唯一一件事对我来说有意义,因为为什么这不起作用是我正在加载两个不同的 session ,因为我的持久层是如何设置的,并且过滤器抓取了错误的 session 。

这是我的 Controller 中的方法,我从数据库中查找用户并导致惰性初始化异常,因为它没有从用户对象中检索角色。

@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String edit(@PathVariable final Integer id, final ModelMap modelMap)
{
final User user = userDao.find(id); ******This causes the lazy init exception

if (user != null)
{
modelMap.addAttribute("userInstance", user);
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));
return "/user/edit";
}
return "redirect:/user/list";
}

这是我的相关设置:

Web.xml:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/board-servlet.xml *****This file references the file with entityManager declared*****
/WEB-INF/board-security.xml
</param-value>
</context-param>

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
<servlet-name>board</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>board</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.ico</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>oemInViewFilter</filter-name>
<filter-class>
org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>oemInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>sitemesh</filter-name>
<filter-class>
com.opensymphony.module.sitemesh.filter.PageFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>sitemesh</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>

board-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

****This is what pulls in my entityManager
<import resource="classpath:persistence-spring-beans.xml"/>

<mvc:annotation-driven/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000"/>
</bean>

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:message"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>

</beans>

持久性-spring-beans.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

<context:annotation-config/>
<context:component-scan base-package="com.something" use-default-filters="true"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="prodPersistenceUnit"/>
<property name="dataSource" ref="c3p0PostgresDataSource"/>
<property name="packagesToScan" value="com.something.persistence.dto"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
</bean>

<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>

<bean id="c3p0PostgresDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="org.postgresql.Driver"/>
<property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/yellow_hammer"/>
<property name="user" value="yellow"/>
<property name="password" value="hammer"/>
<property name="initialPoolSize" value="3"/>
<property name="minPoolSize" value="3"/>
<property name="maxPoolSize" value="50"/>
<property name="idleConnectionTestPeriod" value="200"/>
<property name="acquireIncrement" value="1"/>
<property name="maxStatements" value="0"/>
<!-- 0 means: statement caching is turned off. -->
<property name="numHelperThreads" value="3"/>
<!-- 3 is default -->
</bean>
</beans>

如果相关信息还不够,请告诉我。

编辑UserDao - 这扩展了 GenericDao,我将在下面发布它。

@Dao
public class UserDao extends GenericDao<User>
{
public User findByUsernameAndPassword(final String username, final String password)
{
final Query query = entityManager.createQuery("from User user " + "where user.username = :user " + "and user.password = :pass ")
.setParameter("user", username)
.setParameter("pass", password);

return uniqueResult(query);
}

public List<User> findByRole(final Role roleIn)
{
if (roleIn == null)
{
return null;
}

final Query query = entityManager.createQuery("select user from User user, Role role where role = :roleParam ").
setParameter("roleParam", roleIn);

return query.getResultList();
}
}

通用Dao

public class GenericDao<T extends BaseDto>
{
protected Class<T> entityClass;

@PersistenceContext
protected EntityManager entityManager;

public GenericDao()
{
final ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
}

public T find(final Integer id)
{
return entityManager.find(entityClass, id);
}

public List<T> findAll()
{
final Query query = entityManager.createQuery("from " + entityClass.getSimpleName());
return query.getResultList();
}

public T save(final T t)
{
if (t != null)
{
return t.getId() != null && t.getVersion() != null ? update(t) : create(t);
}

return null;
}

private T create(final T t)
{
entityManager.persist(t);
return t;
}

private T update(final T t)
{
return entityManager.merge(t);
}

public void delete(T t)
{
t = entityManager.merge(t);
entityManager.remove(t);
}

protected T uniqueResult(final Query query)
{
final List results = query.getResultList();
if (results.isEmpty())
{
return null;
}
else if (results.size() == 1)
{
return entityClass.cast(results.get(0));
}

// TODO send notification, multiple results found
return null;
}
}

最佳答案

但是现在!!

让我猜猜:你的应用程序的名称是:board?

正确吗?然后继续阅读剩下的答案!

是的,您有两个实体管理器,甚至两个相同的应用程序上下文(一个应用程序上下文和一个 Web 上下文)——因此您拥有每个 bean 两次!

发生的事情是:你只有一个(相关的)spring 配置文件:'board-servlet.xml'('persistence-spring-beans.xml'包含在该文件中,因此至少它是一个大的逻辑文件)

并且您在“web.xml”中两次从此文件创建上下文:

第一:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/board-servlet.xml *****This file references the file with entityManager declared*****
/WEB-INF/board-security.xml
</param-value>
</context-param>
...
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoaderListener 加载“contextConfigLocation”参数中的文件指定的应用程序上下文。

第二个:

<servlet>
<servlet-name>board</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Dispatcher Servlet 创建 Web 应用程序上下文,其 xml 文件为:

  • 由初始化参数“contextConfigLocation”命名
  • 或者,如果没有这样的参数,它会查找名为“/WEB-INF/-servlet.xml”的文件

(更多详细信息请查看 FrameworkServlet 的 Java 文档)

在您的情况下,没有明确命名的文件,因此它会再次读取“board-servlet.xml”。

你需要做的就是将它们分开:

  • 删除 <import resource="classpath:persistence-spring-beans.xml"/>来自board-servlet.xml
  • 更改 contextConfigLocationweb.xml它指的是 classpath:persistence-spring-beans.xml/WEB-INF/board-security.xml直接
  • (不是 100% 必要)将“context:component-scan”分开,以便组件扫描 board-servlet.xml仅扫描@Controller以及 persistence-spring-beans.xml 中的组件扫描扫描其他( @Service@Component@Repository@Dao )
  • 最后一步:请告诉我现在可以使用了

关于hibernate - OpenEntityManagerInViewFilter 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7003152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com