Hibernate实体中的多个SequenceGenerator

时间:2015-02-16 11:01:20

标签: java hibernate jpa orm hibernate-mapping

是否可以在Hibernate实体类中使用2个序列生成器。我想为我的情况使用两个序列生成器,一个用于主键,另一个用于简单字段。我怎样才能实现同样的目标?

@Data
@Table(name="a_b")
@SequenceGenerator(name = "a1_seq", sequenceName = "a1_seq", allocationSize    = 1)
@SequenceGenerator(name = "b1_seq", sequenceName = "b1_seq", allocationSize = 1)
public class ABC {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "a1_seq")
    private Integer id;

    @Column(name = "c")
    private String c;

    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "b1")
    @Column(name = "b)
    private Integer b;

}

2 个答案:

答案 0 :(得分:1)

主键只能有一个SequenceGenerator:

@Id
@Column(name = "id")
@SequenceGenerator(name = "a1_seq", sequenceName = "a1_seq", allocationSize    = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "a1_seq")
private Integer id;

以及您可以拥有的外键:

@Column(name = "b, columnDefinition="serial")
private Integer b;

应该适用于PostgreSQL。

答案 1 :(得分:0)

在列级别而不是在类级别定义@SequenceGenerator。因此,您可以为两个不同的列创建两个单独的sequenceGenerator - a1_seq和b1。

@Data
@Table(name="a_b")

public class ABC {

  @Id
  @Column(name = "id")
  @SequenceGenerator(name = "a1_seq", sequenceName = "a1_seq", allocationSize    = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "a1_seq")
  private Integer id;

  @Column(name = "c")
  private String c;

  @SequenceGenerator(name = "b1_seq", sequenceName = "b1_seq", allocationSize = 1)
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "b1")
  @Column(name = "b)
  private Integer b;

}

这应该有效。我没有对它进行过测试,但由于在现场级别允许使用SequenceGenerator,它应该可以工作。