使用带有事务支持的Spring Data JPA删除数据并将其插入数据库

时间:2018-08-23 11:47:34

标签: java spring

我在下面的方法中执行以下操作,但出现重复的输入异常

@Transactional(propagation = Propagation.REQUIRED)
public ResponseVo crudOperation(CRUDVo curdVO) {
    Customer customer = repo.getDetails(curdVO.getStoreCode());

    List<Customer> customers = repo.getDetailsById(curdVO.getId());
    repo.delete(customers);

    insertCustomer(curdVO);
}

private void insertCustomer(CRUDVo curdVO) {
    Customer customer;

    for (Short programId : storeVO.getPrograms()) {
        customer = new Customer();          
        customer.setAddress(address);
        customer.setProgram(programId );
        customer.setMobile(curdVO.getMobile());
        repo.save(customer);
    }
}

如果我不使用@Transactional批注,那么上面的工作正常,因为在执行repo.delete(customers)时它会从数据库中删除数据。但是在交易的情况下,其在交易完成后释放数据。由于这个原因,我低于异常

MySQLIntegrityConstraintViolationException: Duplicate entry

Stacktrace ::

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3-4727' for key 'UNQ_KEY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3970)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3906)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2524)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2677)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2073)
    at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2009)
    at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5098)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1994)
    at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:493)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
    ... 153 common frames omitted

请说明为什么在执行repo.delete(customers)语句后不删除数据

0 个答案:

没有答案