Auto Increment A Column With Hibernate
Solution 1
As far as I can see, you can use the Hibernate specific annotation @Generated
. Your field would look something like this:
@Generated(value="GenerationTime.INSERT")
@GenericGenerator(name="fieldGenerator", strategy="sequence")
private X field;
You can read the different types of strategies here.
I'm 90% sure that should work. If it doesn't then let me know.
Solution 2
I checked this and Hibernate allow only one auto column (per table) and it must be defined as a key.
In addition to primary key column If you try to use more than one auto column you will get the error :
[error] o.h.t.h.SchemaUpdate - Incorrect table definition; there can be only one auto column and it must be defined as a key.
You can use sequence or table-use as sequence and save the return value as seq.
simple example of table use as sequence:
@Entity(name = "T1")
@Table(name = "t1")
public class T1 {
@Id
@GeneratedValue
@Column(name = "c_id")
private Long seqId;
public Long getseqId() {
return seqId;
}
public void setseqId(Long sId) {
this.seqId= sId;
}
}
Ace
Updated on June 04, 2022Comments
-
Ace almost 2 years
I have this situation where I need to increment a non primary key column upon insert of every new record. This column is not a primary key. However it has unique constraint. How can I use Hibernate Annotations to accomplish auto increment of this particular column? I know it can be done quite easily for primary keys, but I want exactly same thing to be done for a non primary key column (meaning without using @Id annotation?)
--Thanks
-
Stefan Falk about 9 yearsWould you be so kind and take a look at this: stackoverflow.com/questions/29976363/… maybe you can help me here.
-
Ace almost 7 yearsYou are three years late in answering this question :) I have moved on to NoSQL Technologies completely.
-
MD Ruhul Amin over 3 years
@Id
means primary key and the answer expected for non-primary-key column.