Skip to main content

Customize IdGenerator in JPA, gap between Hibernate and JPA annotations

JPA annotation is like a subset of Hibernate annotation, this means people will find something available in Hibernate missing in JPA. One of the important missing features in JPA is customized ID generator. JPA doesn't provide an approach for developer to plug in their own IdGenerator. For example, if you want the primary key of a table to be BigInteger coming from sequence, JPA will be out of solution.

Assume you don't mind the mixture of Hibernate and JPA Annotation and your JPA provider is Hibernate, which is mostly the case, a solution before JPA starts introducing new Annotation is, to replace JPA @SequenceGenerator with Hibernate @GenericGenerator. Now, let the code talk.
/**
* Ordinary JPA sequence.
* If the Long is changed into BigInteger,
* there will be runtime error complaining about the type of primary key
*/
@Id
@Column(name = "id", precision = 12)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@SequenceGenerator(name = "XyzIdGenerator", sequenceName = "xyz_id_sequence")
public Long getId() {
   return id;
}

In order to generate BigInteger primary key, a custom BigIntegerSequenceGenerator is created.
package com.mycompany.myapp.id;

import org.hibernate.id.SequenceGenerator;
...

public class BigIntegerSequenceGenerator
    extends SequenceGenerator
{
    @Override
    public Serializable generate(SessionImplementor session, Object obj)
    {
        ...
    }
}
Replace the JPA @SequenceGenerator with Hibernate @GenericGenerator, where the strategy can be the class name of IdGenerator.

@Id
@Column(name="id", precision = 32)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
//@SequenceGenerator(name = "XyzIdGenerator", sequenceName = "xyz_id_sequence")
@GenericGenerator(name = "XyzIdGenerator",
        strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
        parameters = {
            @Parameter(name = "sequence", value = "xyz_id_sequence")
        })
public BigInteger getId()
{
   return id;
}
Customized IdGenerator is one of the features in the gap between JPA and Hibernate persistence Annotations. Similar missing features in JPA include other things like @Generated annotation in Hibernate for non-primarykey generated fields.

Comments

Paulo's Blog said…
Hi Jiaqi's thanks for this post.
I'm trying to implement a custom generator for JPA, (Hibernate is the JPA provider in my case), and this article turns out to be very handy. :)
I have two questions, I would appreciate very much your answers.
Is the "xyz_id_sequence" value for the sequenceName arbitrary ? How about the generator "XyzIdGenerator" value
is it arbitrary?
Also, I tried your sample and got
javax.persistence.PersistenceException: org.hibernate.MappingException: could not instantiate id generator exception.
Any ideas?

Thanks !
Paul
Jiaqi Guo said…
xyz_id_sequence is the sequence name in database. XyzIdGenerator is arbitrary, but the generator in @GeneratedValue must match name of @SequenceGenerator.

Basically it means field is a generated value, generated by a sequence type generator named "XyzIdGenerator" and @SequenceGenerator defines what "XyzIdGenerator" is, and it actually is a database sequence named "xyz_id_sequence"
Anonymous said…
Once can use @prePersist and other JPA events to create their own ids.
mark said…
I think your exception is wrong

public Serializable generate(SessionImplementor session, Object obj)
throws HibernateException {

Popular posts from this blog

Spring, Angular and other reasons I like and hate Bazel at the same time

For several weeks I've been trying to put together an Angular application served Java Spring MVC web server in Bazel. I've seen the Java, Angular combination works well in Google, and given the popularity of Java, I want get it to work with open source. How hard can it be to run arguably the best JS framework on a server in probably the most popular server-side language with  the mono-repo of planet-scale ? The rest of this post walks through the headaches and nightmares I had to get things to work but if you are just here to look for a working example, github/jiaqi/angular-on-java is all you need. https://github.com/jiaqi/angular-on-java Java web application with Appengine rule Surprisingly there isn't an official way of building Java web application in Bazel, the closest thing is the Appengine rule  and Spring MVC seems to work well with it. 3 Java classes, a JSP and an appengine.xml was all I need. At this point, the server starts well but I got "No ...

Project Euler problem 220 - Heighway Dragon

This document goes through a Java solution for Project Euler problem 220 . If you want to achieve the pleasure of solving the unfamiliarity and you don't have a solution yet, PLEASE STOP READING UNTIL YOU FIND A SOLUTION. Problem 220 is to tell the coordinate after a given large number of steps in a Dragon Curve . The first thing came to my mind, is to DFS traverse a 50 level tree by 10^12 steps, during which it keeps track of a direction and a coordinate. Roughly estimate, this solution takes a 50 level recursion, which isn't horrible, and 10^12 switch/case calls. Written by a lazy and irresponsible Java engineer, this solution vaguely looks like: Traveler traveler = new Traveler(new Coordinate(0, 0), Direction.UP); void main() { try { traverse("Fa", 0); } catch (TerminationSignal signal) { print signal; } } void traverse(String plan, int level) { foreach(char c:plan) { switch(c) { case 'F': traveler.stepForward(); break; ca...