I'm using hibernate with a MySQL database in my spring MVC project. I have used the @GeneratedValue
annotation to set auto-incremenet on my id fields. So all my entities have this piece of code and everything is working 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 an Oracle database. Now, I have two questions here:
1. What's the best solution to set auto-increment field in oracle? I used this code, but is not working:
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence")
@SequenceGenerator(name="id_Sequence", allocationSize=1)
2(More important question). Is there any way to use a unique annotation to set auto-increment that will work for both MySQL and Oracle ?
1: If you define your own generator, your have to use the generator attribute in @GeneratedValue
. And if you have created your own sequence you have to define the name with sequenceName
otherwise hibernate will create one 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 explicit
@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) a table ID_GEN
with the columns GEN_NAME
, GEN_VALUE
, if schema generation is not available you have to create this table on your own.
You find more complete information from hibernate docs here: http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch05.html#mapping-declaration-id-generator
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.