问题描述
我们有一个before插入触发器,它从序列中获取下一个值。当对象用save()方法持久化时,hibernate从序列中获取值并将其添加到对象中。当事务从Spring的服务层提交时,数据库上的ID值再次增加。如何避免获得nextval()如果对象已经有一个ID ..
这是我可以做的事情..
UserDao
public User saveUser(User user){
session.getCurrentSession.save用户); // line2
return user; // line3
}
UserService
public void saveUserAndWriteToAudit(User user,UserAudit userAudit){
userDao.saveUser(user); // line1
userAudit.setUserId(user.getId); // line4
userAudit.saveUserAudit(userAudit); // line5
}
和User Class
@Entity
public class用户{
@Id
@GeneratedValue(strategy = GenerationType.AUTO,generator =a1)
@SequenceGenerator(name =a1,sequenceName =usersequence)
私人长ID;
/////////////////
}
当光标到达line1且line2用户对象在id属性中为null时。在line2之后,它具有sequence的nextval - 让我说1在line4上,我已经添加了用户的id = 1来使用审查对象..当事务在第5行后被提交时,2被插入到用户的id列中并且1被插入到UserAudit的userId列中。这对我来说没有任何用处:(我怎样才能避免这个问题?谢谢!
创建或替换
触发sa.my_trigger
插入sa.my_table之前每行
(new.id为空)
begin
选择sa.my_sequence.nextval
into:new.id
from dual;
end;
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..
Here is what I ma trying to do..
UserDao
public User saveUser(User user){
session.getCurrentSession.save(user);//line2
return user;//line3
}
UserService
public void saveUserAndWriteToAudit(User user, UserAudit userAudit){
userDao.saveUser(user);//line1
userAudit.setUserId(user.getId);//line4
userAudit.saveUserAudit(userAudit);//line5
}
And the User Class
@Entity
public class User{
@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="a1")
@SequenceGenerator(name="a1", sequenceName="usersequence")
private Long id;
/////////////////
}
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!
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问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!