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

a9wyjsp7  于 2023-04-28  发布在  Java
关注(0)|答案(4)|浏览(99)

在事务中,如果有一个重复的关键字的异常,这发生在第二个持久化,第一个持久化,不做回滚,这一个仍然记录在数据库中。(更新问题,使用更多代码,以更好地检测错误)

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。简体中文

<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
...

但它保存了记录
如果第二个 www.example.com ?
为什么不执行Rollback?

mwngjboj

mwngjboj1#

已更改您的@Transactional (rollbackFor=Exception.class)

@Transactional (rollbackFor=Throwable.class)

检查

j0pj023g

j0pj023g2#

您没有显示实际运行的调用saveService()的代码。调用很可能来自Transactional Proxy后面的位置,因此Spring无法“看到”注解以在该级别启动事务。如果你添加了代码,就能知道。

yh2wf1be

yh2wf1be3#

www.example www.example.com 。因此,第一次调用保存方法提交成功,但第二次调用失败,出现重复条目异常和回滚。
尝试添加propagation=传播。DAO事务方法的强制性。

@Transactional (propagation= Propagation.MANDATORY, rollbackFor=Throwable.class)

这将强制DAO使用服务的相同事务。则回滚将被应用于所有人。
我不认为你会有这个问题与最新版本的Spring,

6ljaweal

6ljaweal4#

在我的例子中,当我更新一个javapojo的时候,你可以使用merge方法而不是update方法来更新java中已经存在的东西。

相关问题