【问题标题】:Spring MVC 3 with Hibernate 4 integrationSpring MVC 3 与 Hibernate 4 集成
【发布时间】:2012-10-24 06:46:29
【问题描述】:

我目前的目标是使用 Hibernate 4 在我的 Web 应用中启用事务管理。

首先,我的 web.xml:

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

    <!-- The definition of the Root Spring Container shared by all Servlets 
        and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
             /WEB-INF/spring/root-context.xml,
             /WEB-INF/spring/appServlet/*-context.xml
        </param-value>
    </context-param>


    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Spring Security -->
    <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>

    <session-config>
        <session-timeout>5</session-timeout>
    </session-config>
</web-app>

mvc-dispatcher-servlet.xml(从 servlet-context.xml 重命名):

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="sec://www.springframework.org/schema/mvc"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing 
        infrastructure -->

    <context:component-scan base-package="com.moose.springmvc.controller" />

    <!-- Enables the Spring MVC @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving 
        up static resources in the ${webappRoot}/resources directory -->
    <mvc:resources mapping="/resources/**" location="resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources 
        in the /WEB-INF/views directory -->
    <beans:bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <mvc:interceptors>
        <beans:bean
            class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <beans:property name="paramName" value="lang" />
        </beans:bean>
    </mvc:interceptors>
</beans:beans>

我的 database-context.xml(从 spring-database.xml 重命名)配置:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

    <context:component-scan base-package="com.moose.springmvc.service,com.moose.springmvc.dao" />

    <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager"/>

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        p:sessionFactory-ref="sessionFactory" />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:packagesToScan="com.moose.springmvc.entity" p:dataSource-ref="dataSource"
        p:configLocation="classpath:hibernate.cfg.xml">
    </bean>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/crud" />
        <property name="user" value="root" />
        <property name="password" value="mysql@123#" />
        <!--  TODO adjust pooling parameters... -->
    </bean>
</beans>

我的 DAO 类:

@Repository
public class UserDAO
{
    @Autowired
    private SessionFactory sessionFactory;

    ...

    public int save(User user)
    {
        return (Integer) sessionFactory.getCurrentSession().save(user);
    }

    ...  
}

我的服务类:

@Service
@Transactional
public class UserService {

    protected static Logger logger = LoggerFactory
            .getLogger(UserService.class);

    @Autowired
    private UserDAO userDAO;


    public Integer createUser(User user){

        return userDAO.save(user);
    }
}

AjaxBootstrapController 类的相关代码:

@Controller
public class AjaxBootstrapController {
    @Autowired
    private UserService userService;

        ....

    @RequestMapping(value = "/userAjaxCustomTag", method = RequestMethod.POST)
    public String processFormAjax(
            @ModelAttribute(value = "user") @Valid User user,
            BindingResult result) {
        if (!result.hasErrors()) {
            userService.createUser(user);
        }
        return "userForm";
    }

编辑

hibernate.cfg.xml 配置:

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/crud</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mysql@123#</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup
        <property name="hbm2ddl.auto">create</property>
         -->
    </session-factory>
</hibernate-configuration>

我得到了新的异常:

org.hibernate.HibernateException: save is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
    at $Proxy31.save(Unknown Source)
    at com.moose.springmvc.dao.UserDAO.save(UserDAO.java:45)
    at com.moose.springmvc.service.UserService.createUser(UserService.java:23)
    at com.moose.springmvc.service.UserService$$FastClassByCGLIB$$60239454.invoke(<generated>)
    at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
    at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
    at com.moose.springmvc.service.UserService$$EnhancerByCGLIB$$419f68a0.createUser(<generated>)
    at com.moose.springmvc.controller.AjaxBootstrapController.processFormAjax(AjaxBootstrapController.java:60)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

配置或者注解有什么问题吗?

【问题讨论】:

  • 看起来有点像UserService类的@Transactional注解没有考虑进去。可以发一下AjaxBootstrapController的相关代码吗?
  • 我已经添加了AjaxBootstrapController的相关代码。谢谢
  • 控制器和所有注入看起来都不错。我认为 Adrian Shum 是对的。

标签: spring hibernate spring-mvc


【解决方案1】:

从您的堆栈跟踪来看,您的 userService 实例周围似乎没有代理,这是非常不正常的,因为它周围应该有一个代理,这是事务处理的方面(假设您使用的是加载时间编织,即Spring中AOP最常用的方式)

不确定是不是你的问题,但我最近遇到了一个类似的问题,结果证明这个问题非常棘手。

我假设您正在使用 Spring 的组件扫描功能

似乎您正在使用 SpringMVC,调度程序 servlet 加载了另一个应用程序上下文文件。 (通常命名为 YOUR_SERVLET_NAME-servlet.xml)

Spring 将其作为主应用程序上下文的单独子应用程序上下文加载。

如果在该 servlet 应用程序上下文中,您再次声明了组件扫描,它将加载一个单独的 UserService 实例,并且,如果您在该应用程序上下文中没有任何事务设置,则此 UserService 实例将没有生成相应的代理(用于交易控制)。

在这种情况下解决方法很简单,只需确保在 servlet 应用上下文中,将组件扫描限制为不扫描主应用上下文中已存在的 bean。

【讨论】:

  • 我更改了 spring-datatabase.xml 上的 packagesToScan。这个包不包含在我的 servlet-context.xml 上的组件扫描中
  • @abiieez:首先创建主应用上下文(通过 spring-database.xml),servlet 应用上下文是主应用上下文的子。主应用程序上下文中的方面不会影响子项中创建的 bean。因为您在 servlet 应用程序上下文中扫描 bean,所以您的服务不会有与事务相关的方面。我的建议是,在主应用程序 ctx 中加载您的 DAO、服务等,并让 MVC 控制器在 servlet 应用程序 ctx 中进行扫描。或者,在您的 servlet 应用程序上下文 xml 中声明
  • 我已经更新了我的配置。现在我得到了新的异常:没有活动的事务,保存是无效的。
  • 我不太确定,但我认为您可以跳过 hibernate.cfg.xml 文件。 LocalSessionFactory 应该单独工作。我只是怀疑你的 hibernate.cfg.xml 告诉 hibernate 使用它自己的数据库连接,而不是你在 Spring 中管理的 DataSource(它在事务控制下)。
  • 我删除了 hibernate.cfg.xml 并且错误消失了。谢谢你的帮助:)
【解决方案2】:

我有几个建议,你可以看看——

您是否使用 CGLIB 为服务生成代理以使用事务?否则,您的服务应该实现一个接口,以便创建 jdk 代理,这些代理使用该接口创建一个代理。

在您的 tx:annotation-driven 标签中额外指定以下内容 -

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

您可以在 spring-database.xml 中的 SessionFactory bean 中配置 Hibernate 配置文件。如果您已将 show-sql 标志配置为 true,则可以通过此查看 SQL 日志,以便更好地了解问题

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
    p:packagesToScan="com.moose.springmvc.dao" p:dataSource-ref="dataSource"
    p:configLocation="specify-path-location-of-hibernate.cfg.xml e.g. /WEB-INF/hibernate/hibernate.cfg.xml">
</bean>

请检查这些。

【讨论】:

  • 我刚刚在我的类路径中添加了 CGLIB。现在也出现了新的异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2012-11-20
  • 2013-01-24
  • 2016-10-05
  • 1970-01-01
相关资源
最近更新 更多