Hibernate – Auto Increment A Column With Hibernate

annotationsauto-incrementgeneratorhibernatestrategy-pattern

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

Best Answer

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.