Automatic ID creation using jpa table generator

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, We have seen a sample CRUD application in jpa in previous article. Here, we will learn how to create generate ids using jpa table generator.

Introduction:

What exactly is automatic ID generation? As its names suggests, They generate automatic identifiers. They are mainly useful for primary keys to be stored in the database for any table. Primary keys are unique for every row and they need not have special meaning outside the system. Hence automatic id generation technique is useful for the same.

JPA Table Generator:

Java Persistence API provides some automatic id generation strategies like sequence generator,jpa table generator, jpa auto generator and identity generator. Here we will see an example of jpa table generator.

Some key points:

  • Suitable, flexible and portable way to generate automatic ids for different databases.
  • You can store multiple sequences within the same table.

The characteristics for creating a table:

  • First column should be used to identify sequence names. It is string.
  • The first column is the primary key.
  • Second column stores integer value of sequence.
  • These values represent the last generated value using jpa table generator strategy.
  • Every sequence represents a separate row in this table

JPA Table Generator Example:

As we know about it now, let us try to implement a simple program for the same. We know how to create a jpa project in eclipse.

Create table for storing sequences:

Create two tables in MySQL. employee table and id_gen table.

  • Employee table represents our Employee entity in JPA
  • id_gen table stores the names of sequences and their values. jpa table generator uses this table.

id_gen    employee

Create Employee entity:

Create Employee entity as follows:

You will notice three annotations here:

The @TableGenerator annotation:

  • Specifies the name of the generator using name attribute i.e. name = "employee_gen" .
  • Specifies the name of the database table that will be used for generating automatic ids. i.e. table = "id_gen".
  • Specifies primary column name which identifies each sequence stored in the form of row. i.e. pkColumnName="gen_name" .
  • Specifies the value of number generated using jpa table generator i.e. valueColumnName="gen_value" .
  • Specifies the value should be incremented by 100 using allocationSize=100

The @Id annotation species that the filed idemployee is used as primary key in the database.

The @GeneratedValue annotation:

  • Specifies generation strategy used is table with strategy = GenerationType.TABLE .
  • Specifies the name of TableGenerator with generator = "employee_gen" .

Now simply write a program to create and persist entites.

 

You can simply run this program and see that employee record is persisted into the database. Run the program multiple times and you will see multiple records inserted.

I hope this article helps understand jpa table generator.

References for further study :

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

27 thoughts on “Automatic ID creation using jpa table generator

  • Pingback:JPA Many to One mapping | theJavaGeek

  • Pingback:jpa embeddable annotation | theJavaGeek

  • Pingback:JPA many to many mapping | theJavaGeek

  • Pingback:JPA Single Table Inheritance Example | theJavaGeek

  • Pingback:JPA table per concrete class example | theJavaGeek

  • Pingback:JPA Joined Inheritance Example | theJavaGeek

  • Pingback:Jpa ElementCollection annotation | theJavaGeek

  • Pingback:JPA one to one mapping | theJavaGeek

  • Pingback:JPA AttributeOverride annotation. | theJavaGeek

  • October 16, 2014 at 10:19 pm
    Permalink

    Will the generator automatically create different rows for each entity? For instance, I would like to define the table generator globally, so I put it in an orm.xml file. The following is the element I use to define it:

    I leave off the pk-column-value attribute because I assume that since this is a global setting, that would cause each entity to use the same row for its sequence. So in leaving this off, will the provider create a different sequence (row) for each entity using this generator? Is there a way to define the value for the name of each entity’s sequence in the pk-column-name?

    Reply
    • October 16, 2014 at 10:21 pm
      Permalink

      Looks like the XML was stripped from my last comment. Basically, it was the “table-generator” element, using the “name”, “table”, “pk-column-name”, and “value-column-name” attributes.

      Reply
    • October 17, 2014 at 11:41 am
      Permalink

      Hi Michael,
      What I understand from your question is that you are using same generator for generation of ids for multiple entities. Right now I am not fully sure about it and I will answer you as soon as I can. Meanwhile this stackoverflow question may be a little bit helpful.

      I will get back on this after experimenting a little 🙂 . Your question will be adding up to my knowledge too.

      Reply
  • Pingback:creating jsf ejb jpa application using eclipse and wildfly - theJavaGeek

  • June 2, 2015 at 1:24 pm
    Permalink

    hi prasad kharkar

    please help me, i found exception when run this tutorial

    how to fix ?
    ———————-
    [EL Warning]: 2015-06-02 14:51:36.794–UnitOfWork(1316216479)–Exception [EclipseLink-4011] (Eclipse Persistence Services – 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Error preallocating sequence numbers. The sequence table information is not complete.
    Exception in thread “main” Local Exception Stack:
    Exception [EclipseLink-4011] (Eclipse Persistence Services – 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Error preallocating sequence numbers. The sequence table information is not complete.
    at org.eclipse.persistence.exceptions.DatabaseException.errorPreallocatingSequenceNumbers(DatabaseException.java:150)
    at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:73)
    at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:257)
    at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:532)
    at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1067)
    at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:361)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:320)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:486)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4290)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4235)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
    at com.thejavageek.jpa.entities.Test.main(Test.java:33)

    Reply
  • April 3, 2016 at 4:26 pm
    Permalink

    [EL Warning]: 2016-04-03 16:25:11.391–UnitOfWork(1790161696)–Exception [EclipseLink-4011] (Eclipse Persistence Services – 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Error preallocating sequence numbers. The sequence table information is not complete.
    Exception in thread “main” Local Exception Stack:
    Exception [EclipseLink-4011] (Eclipse Persistence Services – 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
    Exception Description: Error preallocating sequence numbers. The sequence table information is not complete.
    at org.eclipse.persistence.exceptions.DatabaseException.errorPreallocatingSequenceNumbers(DatabaseException.java:150)
    at org.eclipse.persistence.sequencing.StandardSequence.getGeneratedVector(StandardSequence.java:73)
    at org.eclipse.persistence.sequencing.Sequence.getGeneratedVector(Sequence.java:257)
    at org.eclipse.persistence.internal.sequencing.SequencingManager$Preallocation_Transaction_NoAccessor_State.getNextValue(SequencingManager.java:468)
    at org.eclipse.persistence.internal.sequencing.SequencingManager.getNextValue(SequencingManager.java:1067)
    at org.eclipse.persistence.internal.sequencing.ClientSessionSequencing.getNextValue(ClientSessionSequencing.java:70)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:361)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.assignSequenceNumber(ObjectBuilder.java:320)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.assignSequenceNumber(UnitOfWorkImpl.java:486)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4290)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4235)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
    at com.thejavageek.jpa.Test1.main(Test1.java:25)

    please help me i wasted lot of time but still not able to resolve it

    Reply
    • April 3, 2016 at 10:19 pm
      Permalink

      Did you verify whether the sequence name is existing in your database table?

      Reply
  • Pingback:Relationship- One to One

    • June 7, 2016 at 10:44 am
      Permalink

      Hi, It would be great if you could give due credit to my blog when you are using images, article and code examples from mine.

      Regards,
      Prasad Kharkar

      Reply
      • July 2, 2016 at 7:19 am
        Permalink

        Solution to fix this problem:
        In the javageek DB do these:
        create table id_gen ( gen_name VARCHAR(80), gen_val INT (11), Primary Key (gen_name));
        insert into id_gen (gen_name, gen_val) values(“Emp_Gen”,0);

        Fix the Employee :
        @TableGenerator(name = “employee_gen”, table = “id_gen”,
        pkColumnName = “gen_name”,
        pkColumnValue = “Emp_Gen”,
        valueColumnName = “gen_val”,
        initialValue=0, allocationSize = 100)
        @Id
        @GeneratedValue(strategy = GenerationType.TABLE, generator = “employee_gen”)
        private int idEmployee;

        Reply
  • Pingback:JPA Many to One mapping

  • June 30, 2016 at 4:38 pm
    Permalink

    Getting below exception

    Exception [EclipseLink-4002] (Eclipse Persistence Services – 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘world.id_gen’ doesn’t exist
    Error Code: 1146
    Call: UPDATE id_gen SET SEQ_COUNT = SEQ_COUNT + ? WHERE gen_name = ?
    bind => [2 parameters bound]
    Query: DataModifyQuery(name=”gen_val” sql=”UPDATE id_gen SET SEQ_COUNT = SEQ_COUNT + ? WHERE gen_name = ?”)
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)

    Reply
    • November 16, 2016 at 8:24 pm
      Permalink

      Hi Hitesh,

      A bit late maybe, but if it’s still relevant: seems like you added the table íd_gen’ to the database ‘world’ (MySQL example database?).

      Kind regards,

      Henk van der Meer.

      Reply
      • July 21, 2017 at 5:57 pm
        Permalink

        getting error..
        Internal Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the varchar value ‘inv_gen’ to data type int.

        Reply
  • July 18, 2016 at 1:43 pm
    Permalink

    Hi
    I want to use custom id generator using JPA. Currently every provider has its own way or own annotations to use customm Id generator.
    My Purpose is, user chould be able to change provider jars only ( like eclipselink, hibernate) etc. Rest of code should not be changed.
    Could you please suggest proper way ?

    Reply
  • September 26, 2016 at 12:49 pm
    Permalink

    Hi Prasad Thanks a lot… after 2 days struggle i resolved this Composite PK auto generation

    Reply
  • January 24, 2018 at 12:05 pm
    Permalink

    Hi Prasade

    I would like to create a custom id generator using 20 digit id. Can you please suggest an example for the same

    Thanks
    Beena

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *