Java 使用oracle在休眠中自动递增
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22300980/
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
Auto Increment in hibernate using oracle
提问by Pratik Joshi
I am new to hibernate and I want to insert primary number in my table for unique identification. I am using Oracle as my database so do I need to create sequence in oracle to get auto increment generation number ?
我是 hibernate 的新手,我想在我的表中插入主号码以进行唯一标识。我使用 Oracle 作为我的数据库,所以我需要在 oracle 中创建序列来获取自动增量代号吗?
I am using below code but it is not working. I have not created any sequence yet.
我正在使用下面的代码,但它不起作用。我还没有创建任何序列。
@Id
@Column(name = "id" )
@GeneratedValue ( strategy = GenerationType.TABLE)
I have used AUTO
, SEQUENCE
and IDENTITY
but nothing works for me.
我已经使用AUTO
,SEQUENCE
并IDENTITY
但没有为我工作。
回答by Java_User
You can ue this @GeneratedValue(strategy=GenerationType.AUTO)
你可以用这个 @GeneratedValue(strategy=GenerationType.AUTO)
@Id
@Column(name = "id" )
@GeneratedValue(strategy=GenerationType.AUTO)
回答by seph
this is one way of using Oracle sequence in a JPA mapped entity:
这是在 JPA 映射实体中使用 Oracle 序列的一种方法:
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE_NAME")
@SequenceGenerator(name = "SEQUENCE_NAME", sequenceName = "SEQUENCE_NAME", allocationSize = 1, initialValue = 1)
In this way your persist() method will ask for the next value of the sequence in order to use it as ID for your entry.
通过这种方式,您的 persist() 方法将询问序列的下一个值,以便将其用作您输入的 ID。
回答by Not a bug
In GenerationType.TABLE
option, ID value will be filled with the column of other table.
在GenerationType.TABLE
选项中,ID 值将填充到其他表的列中。
If you are using strategy=GenerationType.TABLE
you will require to mention the Table from where your ID will be filled.
如果您正在使用,strategy=GenerationType.TABLE
您将需要提及填写您的 ID 的表格。
For example,
例如,
@GeneratedValue(strategy=GenerationType.TABLE, generator="course")
@TableGenerator(
name="course",
table="GENERATOR_TABLE",
pkColumnName = "key",
valueColumnName = "next",
pkColumnValue="course",
allocationSize=30
)
And for other option, you can use GenerationType.AUTO
option, and let hibernate decide which option to choose according to databse.
对于其他选项,您可以使用GenerationType.AUTO
选项,并让 hibernate 根据数据库决定选择哪个选项。
@Id
@Column(name = "id" )
@GeneratedValue (strategy = GenerationType.AUTO)
And make sure that you properly configured hibernate.cfg.xml
file.
并确保您正确配置了hibernate.cfg.xml
文件。