Spring Data JPA + Oracle Trigger将ID递增两次

时间:2018-12-13 15:36:48

标签: oracle hibernate jpa spring-data-jpa database-trigger

我使用以下技术堆栈:

  • spring-boot-starter-data-jpa
  • 用于连接池的HikariCP
  • Oracle数据库

我的实际代码与此相似。

   /// My trigger looks like this
   CREATE OR REPLACE TRIGGER FILE_BRI
     BEFORE INSERT
     ON FILE
     FOR EACH ROW
     BEGIN
       SELECT FILE_SEQ.NEXTVAL INTO :NEW.ID FROM DUAL;
     END;
   ///

   public class FILE implements Serializable {
          @Id
        @SequenceGenerator(
                name = "FILE_SEQ",
                sequenceName = "FILE_SEQ",
                allocationSize = 1)
        @GeneratedValue(
                strategy = GenerationType.SEQUENCE,
                generator = "FILE_SEQ"
        )
        private long id;
    }

    public class ServiceA () {

        @Transactional(propagation = REQUIRES_NEW, isolation = READ_COMMITTED) 
        public File insertFile() {
         // Below line returns the inserted File object with ID as '58496'
           return fileRepository.save(file)
        }

        @Transactional(propagation = REQUIRES_NEW, isolation = READ_COMMITTED) 
        public AccessControl insertAccessControl() {
        // Below line results in 'SQLIntegrityConstraintViolationException' (full error at the bottom of this post)
            return accessControlRepository.save(accessControlFile)
         }
     }

     Public class FileProcessor() {
       ServiceA serviceA;
       public void someMethod() {
         // insert the file and get the inserted record
           File insertedFile = serviceA.insertFile(file);

         // get the ID from the inserted file and make another insert into another table
           serviceA.insertAccessControl(insertedFile.getId()); // inserted file ID is '58496'
        }
     }

这是我的调查:

当我验证表“ FILE”中插入的记录的ID为“ 58497”时,但是repository.save()返回了另一个值。 当我在表“ ACCESS_CONTROL_FILE”上进行第二次插入时,FILE_ID为'58496',这会导致以下错误,因为ID为'58496'的FILE不存在。

  

由以下原因引起:java.sql.SQLIntegrityConstraintViolationException:ORA-01400:无法将NULL插入(“ DB_OWNER”。“ ACCESS_CONTROL_FILE”。“ FILE_ID”)

我不知道为什么repository.save()返回的ID(即ID = 58496)与数据库中实际插入的ID(584 = 97)不同!

我已经研究了在互联网上可以找到的与“传播和隔离”相关的所有选项。

1 个答案:

答案 0 :(得分:0)

如评论中所述,似乎是数据库触发器引起了该问题。禁用触发器,让JPA管理ID生成。