我们有一个前插入触发器,它从序列中获取下一个值.当使用 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 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!