休眠、id、oracle、序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5331005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hibernate, id, oracle, sequence
提问by kneethan
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.
我的数据库是 Oracle,我的 id 列值是一个 Oracle 序列,这个序列是由一个触发器执行的,所以,在插入每一行之前,这个触发器使用这个序列来获取 id 值。所以我很困惑我应该在我的实体类中定义哪个 id 策略生成。
@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..
真的很困惑,有人可以对这个主题有所了解吗?请解释清楚..
采纳答案by jomaora
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:
我还有一个项目,其中一个 Oracle DB 为我的 @Entity 类提供数据。正如您所说,序列通过触发器为表的 PK 生成 id。这是我在其中一个类中使用的注释:
@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.
这是您在帖子中展示的第二种语法。Java 代码中没有调用触发器,因为触发器由数据库管理。我记得如果我不想出现问题,我必须在数据库中同时拥有序列和触发器。触发器询问要插入的行的 id 是 null 还是 = 0。在这种情况下,调用序列 LOG_SEQ。
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.
因此,如果您为实体的 @Id 提供一个值,则它可以插入到数据库中(如果该 Id 不存在)并且不会调用该序列。尝试查看触发器的代码以确切了解它发生了什么。