Hibernate,id,oracle,序列 [英] Hibernate, id, oracle, sequence

查看:111
本文介绍了Hibernate,id,oracle,序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库是Oracle,我的id列值是一个Oracle序列,这个序列是由一个触发器执行的,所以,在插入每一行之前,这个触发器使用这个序列来获得id值。所以我很困惑,在我的实体类中应该定义哪种id策略生成。

  @GenericGenerator(name =generator, strategy =increment)
@Id
@GeneratedValue(generator =generator)

  @Id 
@GeneratedValue(strategy = GenerationType.AUTO,generator =idGenerator)
@SequenceGenerator(name =idGenerator,sequenceName =ID_SEQ)

  @Id 
@GeneratedValue(strategy = GenerationType.AUTO)

真的很困惑,难道有人会对这个问题有所了解吗?请解释清楚。

解决方案

我也有一个项目,其中有一个Oracle数据库提供数据给我的@Entity类。正如你所说的,一个序列通过触发器为表格的PK生成ID。这是我在其中一个类中使用的注释:

$ p $ @Id
@GeneratedValue(strategy = GenerationType。 AUTO,generator =G1)
@SequenceGenerator(name =G1,sequenceName =LOG_SEQ)
@Column(name =ID,unique = true,nullable = false,precision = 22,scale = 0)
public int getId(){
return this.id;
}

这是您在文章中显示的第二种语法。
在Java代码中没有调用触发器,因为触发器由数据库管理。我记得如果我不想遇到问题,我必须在数据库中同时拥有序列和触发器。触发器询问要插入的行的id是否为null或= 0。在这种情况下,调用序列LOG_SEQ。因此,如果您为实体的@Id提供值,则可以将其插入数据库(如果该ID不存在),并且序列不会是调用。试着看触发器的代码,看看它发生了什么。


My database is Oracle, and my id column value is an Oracle sequence, this sequence is executed by a trigger, so, before each row is inserted this trigger use this sequence to get the id value. So I am confused in which id strategy generation should I define in my entity class.

@GenericGenerator(name = "generator", strategy = "increment")
@Id
@GeneratedValue(generator = "generator")

or

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "idGenerator")
@SequenceGenerator(name="idGenerator", sequenceName="ID_SEQ")

or

@Id
@GeneratedValue(strategy = GenerationType.AUTO)

Really confused, Could someone shed some light on this subject? Please explain clearly..

解决方案

I had also a projet where an Oracle DB that provides the data to my @Entity classes. As you said, a sequence generates the id for the PK of the table via a trigger. This was the annotations that I used in one of these classes:

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "G1")
@SequenceGenerator(name = "G1", sequenceName = "LOG_SEQ")
@Column(name = "ID", unique = true, nullable = false, precision = 22, scale = 0)
public int getId() {
    return this.id;
}

This is the second syntax that you have showed in your post. There's no call to the trigger in the Java code because the trigger is managed by the DB. I remember that I had to have the sequence and the trigger at the same time in the DB if I didn't wanted to have problems. The trigger asked if the id of the row to insert is null or = 0. In this case the sequence LOG_SEQ is called.

So if you provide a value to the @Id of your entity it could be inserted in the DB (if that Id doesn't exist) and the sequence would not be called. Try to see the code of the trigger to see exactly what it happens.

这篇关于Hibernate,id,oracle,序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆