In Hibernate 6.5 the @GenericGenerator
has been deprecated in favor of @IdGeneratorType
, which according to the documentation is not supposed to work with the JPA-defined annotation jakarta.persistence.GeneratedValue
:
JavaDoc for @IdGeneratorType
annotation:
/**
* ...
* and we may use it as follows:
* <pre>
* @Id @CustomSequence(name = "mysequence", startWith = 0)
* private Integer id;
* </pre>
* <p>
* We did not use the JPA-defined {@link jakarta.persistence.GeneratedValue}
* here, since that API is designed around the use of stringly-typed names.
* The {@code @CustomSequence} annotation itself implies that {@code id} is
* a generated value.
*/
Our application uses Hibernate with a Sequence
- or an Identity
-Strategy depending on the DBMS in production. Prior to Hibernate 6.5 we relied on the article from Vlad Mihalcea: How to replace the TABLE identifier generator with either SEQUENCE or IDENTITY in a portable way, by defining the default mapping using java code with @GeneratedValue
. Additional XML metadata is provided at runtime to override the strategy. For MySQL we still use the Identity
-Strategy as there is no native support for Sequences yet.
@MappedSuperclass
public abstract class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = CustomSequenceGenerator.STRATEGY_NAME)
@GenericGenerator(name = CustomSequenceGenerator.STRATEGY_NAME, type = CustomSequenceGenerator.class, parameters = {
@Parameter(name = "initial_value", value = "1"),
@Parameter(name = "increment_size", value = "1")
})
@Nullable
public Long getId() {
return id;
}
...
}
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings xmlns="https://jakarta.ee/xml/ns/persistence/orm"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/persistence/orm https://jakarta.ee/xml/ns/persistence/orm/orm_3_1.xsd"
version="3.1">
<mapped-superclass class="org.example.AbstractEntity">
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
</attributes>
</mapped-superclass>
</entity-mappings>
@GeneratedValue
is part of JPA, so it is also available using XML metadata. The new @IdGeneratorType
is part of Hibernate, which can’t be used in XML because the hbm.xml mappings are deprecated in Hibernate 6.0, right?
Is there a way to achieve a portable strategy with the new @IdGeneratorType
annotation?