java - Spring Transaction 如果这个重复的键给出异常,但它不执行回滚(更新代码以更好地检测错误)

标签 java spring jakarta-ee spring-transactions

在Transaction中,如果key重复出现异常,发生在第二个persist,第一个persist,不做Rollback,这个一直记录在数据库中。 (使用更多代码更新问题以更好地检测错误)

      public interface TemperaturesDao {
        @Transactional (rollbackFor=Throwable.class)
    // @Transactional (rollbackFor=Exception.class) // changed
        void save(JavaTemperatures jT);
    }

    @Repository
    public class TemperaturesDaoImp implements TemperaturesDao{
        @Autowired
        private SessionFactory sf;
        @Transactional (rollbackFor=Throwable.class)
        // @Transactional (rollbackFor=Exception.class) // changed
        public void save(JavaTemperatures jT) {
            Session session = sf.getCurrentSession();
            session.save(jT);
        }
    }


    public interface TemperaturesService {
        @Transactional (rollbackFor=Throwable.class)
    // @Transactional (rollbackFor=Exception.class) // changed
        void saveService();
    }

    @Service("temperaturesServiceImp")
    public class TemperaturesServiceImp implements TemperaturesService{
        @Autowired
        TemperaturesDao tempeDao;

        @Transactional (rollbackFor=Throwable.class)
    // @Transactional (rollbackFor=Exception.class) // changed
        public void saveService() {
            JavaTemperatures jT = new JavaTemperatures();
            jT.setKey("key2");
            tempeDao.save(jT); // This is registered in the database at the end of the veService

            jT = new JavaTemperatures();
            jT.setKey("key1"); // This key exists in the database
            tempeDao.save(jT); // This record gives exception at the end of the saveService
        }
    }


    public class BaseBeanImp implements Serializable{
        ...
    }

    @Controller
    @Scope("session")
    public class ComparaBean extends BaseBeanImp implements Serializable {
        private static final long serialVersionUID = 1L;
        @Autowired
        private TemperaturesService tempeService;

        public String doSave() {
            tempeService.saveService() ;
            return null;
        }
    }

    **index.xhtml**
    <h:commandButton value="Save" action="#{comparaBean.doSave}" />

applicationContext.xml

<beans xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" >
<property name="driverClassName" value="com.mysql.jdbc.Driver" > </property>
<property name="url" value="jdbc:mysql://redhada.org:3306/db" > </property>
<property name="username" value="username" > </property>
<property name="password" value="password" ></property>
<property name="testOnBorrow" value="true" > </property>
<property name="validationQuery" value="SELECT 1" ></property>
<property name="timeBetweenEvictionRunsMillis" value="1200000" ></property>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" >
<property name="dataSource" ref="dataSource" > </property>
<property name="annotatedClasses" >
    <list>
    <value>com.redhada.model.JavaTemperatures</value>
    </list>
</property>
<property name="hibernateProperties">
<props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop></property>
</bean>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package="com.redhada"></context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
 class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory" > </property>

控制台:

263194 [http-8080-Processor23] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000
263194 [http-8080-Processor23] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry 'clave31' for key 1
263195 [http-8080-Processor23] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
...
Caused by: java.sql.BatchUpdateException: Duplicate entry 'key1' for key 1
...
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry 'key1' for key 1
...

但是它保存了记录

如果第二个 tempeDao.save 给出异常,为什么会持续存在?

为什么不做回滚?

最佳答案

改变了你的@Transactional (rollbackFor=Exception.class)

@Transactional (rollbackFor=Throwable.class)

并检查。

关于java - Spring Transaction 如果这个重复的键给出异常,但它不执行回滚(更新代码以更好地检测错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13825771/

相关文章:

Spring批处理重复步骤以永无止境的循环结束

java - 持久化动态属性和查询

java - Hashmap.keySet()、foreach 和删除

java - 如何在 PCF 中运行的 Spring Boot 应用程序中加载更改的环境变量而不重新启动应用程序?

java - Spring MVC @RequestMapping 参数问题

java - MyBatis - 映射树数据结构

java - 如何在 Java Web 应用程序之间共享通用组件?

java - 具有更多注入(inject) EJB 实例的无状态 EJB

java - 获取 Activity 为空

java - 观察变量的变化