Hibernate Sequence Id Specification

我怕爱的太早我们不能终老 提交于 2019-12-08 03:10:23

问题


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.


回答1:


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!




回答2:


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 )



来源:https://stackoverflow.com/questions/44741990/hibernate-sequence-id-specification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!