Tuesday, December 20, 2011

Auto generated ID's for MySql and Oracle using Hibernate

Here you have auto generated ID's examples using Hibernate with Oracle and MySql databases.

Oracle

...

@Entity
@Table(name = "grupo")
public class Grupo implements GenericModel {


@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GRUPO_ID_SEQ")
@SequenceGenerator(name = "GRUPO_ID_SEQ", sequenceName = "GRUPO_ID_SEQ", allocationSize = 1)
@Column(nullable=false)
private Long id_grupo;

...

Sequence GRUPO_ID_SEQ must exist in Oracle database.


Considering that MySql does not have sequences, if you try to use the code above with MySql you will get a runtime exception:


Caused by: org.hibernate.MappingException: Dialect does not support sequences
at org.hibernate.dialect.Dialect.getSequenceNextValString(Dialect.java:619)
at org.hibernate.id.SequenceGenerator.configure(SequenceGenerator.java:88)
at org.hibernate.id.SequenceHiLoGenerator.configure(SequenceHiLoGenerator.java:66)
at org.hibernate.id.IdentifierGeneratorFactory.create(IdentifierGeneratorFactory.java:127)

MySQL


...
@Entity
@Table(name = "grupo")
public class Grupo implements GenericModel {


@Id
@GeneratedValue
@Column(nullable=false)
private Long id_grupo;
...

The field id_grupo must be marked as auto increment in MySql.




No comments:

Post a Comment