Home > Java > body text

Hibernate 6 - IdentifierGenerator - Default generator that delegates to NULL IDs

WBOY
Release: 2024-02-14 20:48:07
forward
327 people have browsed it

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.

Question content

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;
    }
    
}
Copy after login

and its usage

@GenericGenerator( name = "CustomIdGenerator",
                   type = domain.util.CustomIdGenerator.class )
public class Tournament
{
    @Id
    @GeneratedValue( strategy = GenerationType.IDENTITY, generator = "CustomIdGenerator" )
    private Long id;
}
Copy after login

Any ideas on how to adapt this code to work with hibernate 6?

WORKAROUND

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 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;
  }
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!