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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:49:28  来源:igfitidea点击:

Auto Increment in hibernate using oracle

javahibernateprimary-key

提问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, SEQUENCEand IDENTITYbut nothing works for me.

我已经使用AUTOSEQUENCEIDENTITY但没有为我工作。

回答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.TABLEoption, ID value will be filled with the column of other table.

GenerationType.TABLE选项中,ID 值将填充到其他表的列中。

If you are using strategy=GenerationType.TABLEyou 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.AUTOoption, 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.xmlfile.

并确保您正确配置了hibernate.cfg.xml文件。