Our Java application have to use both SQL-Server and Oracle. IDENTITIES are used with SQL Server, and SEQUENCE-TRIGGER with Oracle.
Is there way in Hibernate to generate ID with both SEQUENCEs and IDENTIES ?
Thanks.
Our Java application have to use both SQL-Server and Oracle. IDENTITIES are used with SQL Server, and SEQUENCE-TRIGGER with Oracle.
Is there way in Hibernate to generate ID with both SEQUENCEs and IDENTIES ?
Thanks.
As you have two different application instances you can try to use so called "native" generator which will automatically use correct generator for your datasource based on the dialect. So for oracle it will use SequenceGenerator and for MS SQL it will use the IdentityGenerator. The following code shows the usage (there may be some lags as I don't have MsSQL or Oracle running).
@Entity
@Table(name = "SOME_TABLE")
@SequenceGenerator(name = "SOME_SEQUENCE", allocationSize = 1, sequenceName = "SOME_SEQUENCE")
public class SomeEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SOME_SEQUENCE")
@Column(name = "ID", unique = true)
private Long id;
}
As you can see we are passing the Oracle sequence name with parameters otherwise the sequence with name HIBERNATE_SEQUENCE will be used.
While I agree with the accepted text answer, I disagree with the code, at least for my versions. GenerationType.AUTO
resulted in an invalid generation configuration for SQL Server for me (did not seem to select Identity). Here is my solution for dual database MSSQL / Oracle using Hibernate Core 5.4.30 + SQLServer2012Dialect + Oracle12cDialect:
@Id
@GenericGenerator(name = "MY_GENERATOR", strategy = "native",
parameters = {
@org.hibernate.annotations.Parameter(name = "schema", value="MY_SCHEMA"),
@org.hibernate.annotations.Parameter(name = "sequence_name", value="MY_SEQUENCE")
}
)
@GeneratedValue(generator = "MY_GENERATOR")
private Long id;
You should be able to add other parameters such as allocation size to the parameter list, I believe.