Martin Irigaray
Martin Irigaray

Reputation: 675

Hibernate Sequence Id Specification

I have this annotation to specify a sequence id:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "parametro_seq_gen")
@SequenceGenerator(name = "parametro_seq_gen", sequenceName = "PARAMETROS_SQ",
      allocationSize = 1, initialValue = 1)

I find it very verbose to repeat on all my entities.

Is there any way to create a custom annotation or something ? I want to specify only the sequence name.

Upvotes: 1

Views: 2605

Answers (2)

Vlad Mihalcea
Vlad Mihalcea

Reputation: 154090

That's easy!

Just create a package-info.java where entities are stored and provide the global @GenericGenerator there:

@GenericGenerator(
    name = "pooled",
    strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
    parameters = {
        @Parameter(name = "sequence_name", value = "sequence"),
        @Parameter(name = "initial_value", value = "1"),
        @Parameter(name = "increment_size", value = "5"),
    }
)
package com.vladmihalcea.book.hpjp.hibernate.identifier.globalsequence;

Then your entities can share the pooled generic generator as follows:

@Entity(name = "Post")
public class Post {

    @Id
    @GeneratedValue(generator = "pooled")
    private Long id;
}

@Entity(name = "Announcement")
public class Announcement {

    @Id
    @GeneratedValue(generator = "pooled")
    private Long id;
}

You need to use @GenericGenerator since @SequenceGenerator is not applicable to packages.

That's it!

Upvotes: 3

Liping Huang
Liping Huang

Reputation: 4476

Yes, you can do it with the custom annotation or something else in the hack way, but what I suggest is to using the live template ( I'm using IDEA ) enter image description here

enter image description here

Upvotes: 0

Related Questions