Hibernate - how to set auto-increment in both mysql and oracle databases?

I am using hibernate with a MySQL database in my spring MVC project. I used the @GeneratedValue annotation to set auto-incremenet in my id fields. So, all of my entities have this piece of code, and everything works as expected:

 @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "id") private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 

At this time, I want to switch to the Oracle database. Now I have two questions:

1. What is the best solution to set auto-increment field in oracle? I used this code but does not work:

 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence") @SequenceGenerator(name="id_Sequence", allocationSize=1) 

2 (More important question). Can I use a unique annotation to set auto-increment, which will work for both MySQL and Oracle ?

+6
source share
1 answer

1 If you define your own generator, you need to use the generator attribute in @GeneratedValue . And if you created your own sequence, you must define the name using sequenceName , otherwise hibernate will create it for you.

 @SequenceGenerator(name="some_gen", sequenceName="Emp_Seq") @GeneratedValue(generator="some_gen") 

2 The most flexible (and portable) way is to use the TABLE strategy

 @GeneratedValue(strategy=GenerationType.TABLE) 

or more explicitly

 @GeneratedValue(generator="some_gen") @TableGenerator(name="some_gen", table="ID_GEN", pkColumnName="GEN_NAME", valueColumnName="GEN_VAL") 

This will generate (if schema generation is enabled) the ID_GEN table with columns GEN_NAME , GEN_VALUE , if schema generation is not available, you need to create this table yourself.

Here you will find more complete information from hibernate docs: http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#mapping-declaration-id-generator

0
source

All Articles