事务回滚后,Spring不会关闭hibernate会话

时间:2013-02-05 16:40:48

标签: java spring hibernate

我正在尝试在服务层中捕获ConstraintViolationException并重新抛出用户定义的已检查异常。我正在我的控制器中捕获异常并向我的BindingResult添加一个错误对象。我正在使用声明式事务管理我试图使我的DAO成为一个存储库,并添加了一个PersistenceExceptionTranslationPostProcessor来捕获一个Spring翻译的异常。我还添加了一个txAdvice来回滚所有throwables。我的异常确实被抓住但是我收到错误500:

Hibernate: insert into user (email, password, first_name, last_name, userType) values (?, ?, ?, ?, 1)
[acme]: [WARN ] - 2013-Feb-05 11:12:43 -  SqlExceptionHelper:logExceptions(): SQL Error: 1062, SQLState: 23000
[acme]: [ERROR] - 2013-Feb-05 11:12:43 -  SqlExceptionHelper:logExceptions(): Duplicate entry 'admin' for key 'email_unique'
[acme]: [DEBUG] - 2013-Feb-05 11:12:43 -  HibernateTransactionManager:processCommit(): Initiating transaction commit
[acme]: [DEBUG] - 2013-Feb-05 11:12:43 -  HibernateTransactionManager:doCommit(): Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[] unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
[acme]: [ERROR] - 2013-Feb-05 11:12:43 -  AssertionFailure:<init>(): HHH000099: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in com.test.model.AdminUser entry (don't flush the Session after an exception occurs)
[acme]: [DEBUG] - 2013-Feb-05 11:12:43 -  HibernateTransactionManager:doRollbackOnCommitException(): Initiating transaction rollback after commit exception
org.hibernate.AssertionFailure: null id in com.test.model.AdminUser entry (don't flush the Session after an exception occurs)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:79)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:194)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:156)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:225)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1213)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:402)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:468)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)

我的控制器:

@RequestMapping (method = RequestMethod.POST) 
    @Transactional
    public String registerAdmin(@Valid @ModelAttribute("user") AdminUser user, BindingResult bindingResult, ModelMap model)  {
        if (bindingResult.hasErrors()) {
            return "admin/admins/form";
        } 
        else if (!user.getPassword().equals(user.getConfirmPassword())) {
            bindingResult.addError(new ObjectError("user.confirmPassword", "Passwords don't match"));
            return "admin/admins/form";
        }
        else {
            user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
            try {
                userService.save(user);
                return "redirect:/admin/admins";
            } catch(ApplicationException ce) {
                bindingResult.addError(new ObjectError("user.email", "Email already registered"));
                return "admin/admins/form";
            }

        }

    }

我的Spring配置的一部分:

    <context:component-scan base-package="com.test.dao, com.test.service" />
     <context:property-placeholder location="/WEB-INF/spring.properties"/>  

    <import resource="springapp-security.xml"/>

    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/testdb?zeroDateTimeBehavior=convertToNull"/>
    <property name="username" value="test"/>
    <property name="password" value="test"/>
  </bean>

  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="mappingLocations" value="classpath*:com/test/model/hbm/**/*.hbm.xml" />

    <property name="hibernateProperties">
      <value>
        hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
        hibernate.show_sql=true
      </value>
    </property>
  </bean>

 <tx:annotation-driven />
  <bean id="transactionManager"
            class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
  </bean>
  <tx:advice id="txAdvice">
  <tx:attributes>
  <tx:method name="*" rollback-for="Throwable" />
  </tx:attributes>
</tx:advice>

服务层:

public class UserServiceImpl implements UserDetailsService, UserService {

    private UserDAO dao;


    @Override
    public void save(User c) throws ApplicationException {
        try {
            dao.save(c);
        } catch(DataIntegrityViolationException cve) {
            throw new ApplicationException("email already registered");
        }
    }

如果我没有捕获运行时异常,我没有得到hibernate异常(不要刷新会话..)

1 个答案:

答案 0 :(得分:4)

您可能希望从控制器中删除事务注释并将其添加到服务层。

服务层如下所示。如果服务层抛出了已检查的异常,则可以将其添加到注释中,以便甚至不会尝试提交插入。

public class UserServiceImpl implements UserDetailsService, UserService {

private UserDAO dao;


@Override
@Transactional(rollbackFor=ApplicationException.class)
public void save(User c) throws ApplicationException {
    try {
        dao.save(c);
    } catch(DataIntegrityViolationException cve) {
        throw new ApplicationException("email already registered");
    }
}

当前代码中发生的事情是事务没有被回滚但必须回滚,因为它实际上试图提交数据但是因为数据库约束事务必须回滚。通过使用@Transactional(rollbackFor = ApplicationException.class)强制回滚,它将不允许事务执行提交但它将回滚,你的应用程序仍然会将错误添加到BindingResult。