Hibernate 5 ID AUTO Generation Type for Oracle as Sequence and MySQL as Identity

Daniel Rodríguez :

We have a Java program using Hibernate 5 that can be installed using different DB Engines: Oracle, PostgreSQL or SQL Server. Now we are introducing MySql.

The entities have a Generated Value AUTO identifier.

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
protected Long id;

This worked fine until now. Oracle and PostgreSQL installations are using HIBERNATE_SEQUENCE sequence to generate the id values and SQL Server is using a table generated id (IDENTITY).

With MySQL we would like to use also the table generated id, but Hibernate 5 GenerationType.AUTO on MySQL tries the TABLE generator instead of the IDENTITY generator.

I found this solution by Vlad Mihalcea where using a native generator makes Hibernate to select IDENTITY for MySQL:

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
protected Long id;

That's nice for MySQL, but then the application is no longer working in Oracle (ORA-02289: sequence does not exist). I think Hibernate is then searching for a sequence called native in the Oracle DB.

Is there a solution to keep the ID generation the same for all the other DB engines (Oracle, PostgreSQL and SQL Server) and use the IDENTITY for MySQL?

If not the only solution I can see is to implement the TABLE ID generation in MySQL, but it seems not to have a good performance.

Daniel Rodríguez :

I almost had it in the question, but in case somebody falls in the same situation: calling the generator HIBERNATE_SEQUENCE will make it backwards compatible with Oracle and PostgreSQL (SQL Server will continue using IDENTITY).

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "HIBERNATE_SEQUENCE")
@GenericGenerator(name = "HIBERNATE_SEQUENCE", strategy = "native")
protected Long id;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=356835&siteId=1