使用 Oracle Trigger 从序列生成 id 的 HIbernate 问题

2023-09-19数据库问题
3

本文介绍了使用 Oracle Trigger 从序列生成 id 的 HIbernate 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我们有一个前插入触发器,它从序列中获取下一个值.当使用 save() 方法持久化对象时,hibernate 从序列中获取值并将其添加到对象中.当事务从 Spring 的服务层提交时,数据库上的 ID 值再次增加.如果对象已经有一个 id,我如何避免获取 nextval() ..

We have a before insert trigger that gets the next value from sequence. When the object is persisted with save() method, hibernate gets the value from the sequence and adds it to the object. and when the transaction is committed from Spring's service layer, the ID value is again increased on the database. how do I avoid getting nextval() if the object already has an id..

这就是我想要做的..

用户道

public User saveUser(User user){
      session.getCurrentSession.save(user);//line2
      return user;//line3  
 }

用户服务

public void saveUserAndWriteToAudit(User user, UserAudit userAudit){
  userDao.saveUser(user);//line1
  userAudit.setUserId(user.getId);//line4
  userAudit.saveUserAudit(userAudit);//line5
}

和用户类

 @Entity
  public class User{

     @Id
     @GeneratedValue(strategy=GenerationType.AUTO, generator="a1")
     @SequenceGenerator(name="a1", sequenceName="usersequence")
     private Long id;
     /////////////////
 }

当光标到达第 1 行和第 2 行时,用户对象的 id 属性为空.在第 2 行之后,它具有序列中的 nextval - 比如说 1.在第 4 行上,我已将用户的 id=1 添加到 useraudit 对象中.当在第 5 行之后提交事务时,2 被插入到用户的 id 列中,1 被插入到 UserAudit 的 userId 列中.这对我没有任何意义:(我该如何避免这个问题?谢谢!

When the cursor reaches line1 and line2 user object has null in id attribute. after line2, it has nextval from sequence - lets say 1. on line4, i have added user's id=1 to useraudit object.. when transaction is committed after line 5, 2 is inserted into User's id column and 1 into UserAudit's userId column. This serves no purpose to me :( How do I avoid this issue? Thanks!

推荐答案

只需将触发器更新为仅在未指定 id 时触发.

Just update your trigger to only fire when not given an id.

create or replace
trigger sa.my_trigger
before insert on sa.my_table
for each row
when (new.id is null)
begin
   select sa.my_sequence.nextval
    into :new.id
    from dual;
end;

这篇关于使用 Oracle Trigger 从序列生成 id 的 HIbernate 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同
Why Mysql#39;s Group By and Oracle#39;s Group by behaviours are different(为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同)...
2024-04-16 数据库问题
13

单个列的多个外键
Multiple foreign keys to a single column(单个列的多个外键)...
2024-04-16 数据库问题
7

唯一约束与唯一索引
Unique Constraint vs Unique Index(唯一约束与唯一索引)...
2024-04-16 数据库问题
8

SQL Server:如何限制表包含单行?
SQL Server: how to constrain a table to contain a single row?(SQL Server:如何限制表包含单行?)...
2024-04-16 数据库问题
3

创建分层定义的数据集的扁平表/视图
Creating a flattened table/view of a hierarchically-defined set of data(创建分层定义的数据集的扁平表/视图)...
2024-04-16 数据库问题
4

MySQL:如何做到行级安全(如 Oracle 的 Virtual Private Database)?
MySQL: how to do row-level security (like Oracle#39;s Virtual Private Database)?(MySQL:如何做到行级安全(如 Oracle 的 Virtual Private Database)?)...
2024-04-16 数据库问题
6