One of the new features in Hibernate 6 is the introduction of the IdentifierGenerator interface. In the default generator, Hibernate 6 will delegate to NULL ID as the default implementation. With this new feature, developers can more flexibly customize identity generation for entities. In this article, PHP editor Yuzai will introduce the usage and examples of IdentifierGenerator in Hibernate 6.
I have a specific requirement to manually set and save the id of an entity based on the mapping table in the old system. I created a class that implements this functionality before upgrading to hibernate 6.
The basis of this class is to use the passed id (i.e. non-null) or "let" hibernate use its default mechanism to generate the value.
I had a working version of the code that worked with hibernate
@slf4j public class customidgenerator implements identifiergenerator { @override public serializable generate( final sharedsessioncontractimplementor session, final object obj ) { serializable id = session.getentitypersister( null, obj ).getclassmetadata().getidentifier( obj, session ); if ( id == null || long.parselong( id.tostring() ) <= 0 ) { // if the id is not set or is less than or equal to 0, let hibernate generate it. log.debug( "hibernate will generate a new id for entity [{}]", obj.getclass().getname() ); id = super.generate( session, obj ); // cannot do this anymore! } else { log.debug( "using provided id [{}] for entity [{}]", id, obj.getclass().getname() ); } return id; } }
and its usage
@GenericGenerator( name = "CustomIdGenerator", type = domain.util.CustomIdGenerator.class ) public class Tournament { @Id @GeneratedValue( strategy = GenerationType.IDENTITY, generator = "CustomIdGenerator" ) private Long id; }
Any ideas on how to adapt this code to work with hibernate 6?
I guess as a solution you can do something like the next method since you have the session.
@Slf4j public class CustomIdentifierGenerator implements IdentifierGenerator { @Override public Serializable generate(SharedSessionContractImplementor session, Object obj) { Serializable id = session.getEntityPersister( null, obj ).getClassMetadata().getIdentifier( obj, session ); if (id == null || Long.parseLong(id.toString()) <= 0) { // If the ID is not set or is less than or equal to 0, let Hibernate generate it. log.debug("Hibernate will generate a new ID for entity [{}]", obj.getClass().getName()); String sqlQuery = "SELECT MAX(id) FROM Tournament"; Optional<Long> query = session.createQuery(sqlQuery, Long.class).getResultStream().findFirst(); id = query.get() + 1; } else { log.debug("Using provided ID [{}] for entity [{}]", id, obj.getClass().getName()); } return id; } }
Or use session.createnativequery()
and extract the next value of the sequence.
The above is the detailed content of Hibernate 6 - IdentifierGenerator - Default generator that delegates to NULL IDs. For more information, please follow other related articles on the PHP Chinese website!