Table of Contents
Question content
WORKAROUND
Home Java Hibernate 6 - IdentifierGenerator - Default generator that delegates to NULL IDs

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

Feb 14, 2024 pm 08:48 PM

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

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)