views:

51

answers:

2

It turns out that the following example works when using mysql 5.x, however it doesnt when using an oracle 10g database.

Is there a way to define a unique identifier field that is independant of the database technology?

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private long id;

I have tested this in hibernate and the following exception occurs only when using Oracle:

org.hibernate.MappingException: Dialect does not support identity key generation
+3  A: 

Using a database table is a portable way to generate identifiers.

The simplest way to use a table to generate identifiers is to specify TABLE as the generation strategy:

@Id
@GeneratedValue(strategy=GenerationType.TABLE)
@Column(name="id")
private long id;

The provider will create the default table if you're using schema generation; if not, you must specify an existing table:

@TableGenerator(name="InvTab",
    table="ID_GEN",
    pkColumnName="ID_NAME",
    valueColumnName="ID_VAL",
    pkColumnValue="INV_GEN")
@Id 
@GeneratedValue(generator="InvTab")
@Column(name="id")
private long id;

http://www.oracle.com/technology/products/ias/toplink/jpa/howto/id-generation.html#table

reverendgreen
A: 

I have researched using GenerationType.AUTO and it does appear to be the better option. It allows the JPA implementation to choose whatever is best for the data storage system you are using.

Jacob
The catch with GenerationType.AUTO is that the provider needs to have database permissions to create a table or sequence if it chooses either of those strategies. Normally this is a privileged operation restricted to the DBA. In this case you'll need to ensure the persistent resource is created before the AUTO strategy is able to function.
reverendgreen