Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate: How specify custom sequence generator class name using annotations?

Tags:

hibernate

jpa

I want to specify following hbm configuration using annotations:

<id name="somePK" column="&quot;somePK&quot;" type="long">
            <generator class="com.db.hibernate.KeyGenerator"/>
        </id>

I am not sure how to provide class name with

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")

Do I have to specify @javax.persistence.SequenceGenerator in each entity class?
Can I specify just the class name under @GeneratedValue annotation?

like image 490
Himanshu Yadav Avatar asked Jul 24 '12 13:07

Himanshu Yadav


People also ask

Which annotation is used for a custom database sequence in Hibernate?

In order to customize the sequence name, we can use the @GenericGenerator annotation with SequenceStyleGenerator strategy: @Entity public class User { @Id @GeneratedValue(generator = "sequence-generator") @GenericGenerator( name = "sequence-generator", strategy = "org. hibernate.

How would you implement a custom sequence based id generator?

If you want to use a custom generator, you need to define the generator in a @GenericGenerator annotation and provide the fully-qualified classname as the strategy. You can also configure a set of parameters that will be provided to the configure method when Hibernate instantiates the generator.

How can you define a sequence generated primary key in Hibernate?

IDENTITY: Hibernate relies on an auto-incremented database column to generate the primary key, SEQUENCE: Hibernate requests the primary key value from a database sequence, TABLE: Hibernate uses a database table to simulate a sequence.

What does @GeneratedValue annotation do?

Annotation Type GeneratedValueProvides for the specification of generation strategies for the values of primary keys. The GeneratedValue annotation may be applied to a primary key property or field of an entity or mapped superclass in conjunction with the Id annotation.


1 Answers

please find below set of code which i have used in project for the same.

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "XyzIdGenerator")
@GenericGenerator(name = "XyzIdGenerator",
        strategy = "com.mycompany.myapp.id.BigIntegerSequenceGenerator",
        parameters = {
            @Parameter(name = "sequence", value = "xyz_id_sequence")
        })
public BigInteger getId()
{
   return id;
}


package com.mycompany.myapp.id;

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

public class BigIntegerSequenceGenerator
    extends SequenceGenerator
{
    @Override
    public Serializable generate(SessionImplementor session, Object obj)
    {
        ...
    }
}
like image 128
Jigar Parekh Avatar answered Sep 17 '22 18:09

Jigar Parekh