Hibernate Sequence Id Specification

时间:2017-06-25 00:02:07

标签: java hibernate jpa sequence global

我有这个注释来指定序列id:

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

我觉得重复我所有的实体都非常冗长。

有没有办法创建自定义注释或什么?我只想指定序列名称

2 个答案:

答案 0 :(得分:2)

这很简单!

只需创建一个存储实体的package-info.java,然后在那里提供全局@GenericGenerator

@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;

然后您的实体可以按如下方式共享pooled通用生成器:

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

您需要使用@GenericGenerator,因为@SequenceGenerator不适用于套餐。

那就是它!

答案 1 :(得分:0)

是的,您可以使用自定义注释或黑客方式中的其他内容,但我建议使用实时模板(我使用IDEA) enter image description here

enter image description here