search
HomeJavaHibernate 6 - IdentifierGenerator - Default generator that delegates to NULL IDs

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;
    }
    
}

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?

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<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!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools