简体   繁体   中英

Auto Increment in hibernate using oracle

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 ?

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.

this is one way of using Oracle sequence in a JPA mapped entity:

@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.

You can ue this @GeneratedValue(strategy=GenerationType.AUTO)

@Id
@Column(name = "id" )
@GeneratedValue(strategy=GenerationType.AUTO)

In GenerationType.TABLE option, ID value will be filled with the column of other table.

If you are using strategy=GenerationType.TABLE you will require to mention the Table from where your ID will be filled.

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.

 @Id
 @Column(name = "id" )
 @GeneratedValue (strategy = GenerationType.AUTO)

And make sure that you properly configured hibernate.cfg.xml file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM