gpt4 book ai didi

java - MappedSuperclass - 在子类中更改 SequenceGenerator

转载 作者:IT老高 更新时间:2023-10-28 21:18:18 26 4
gpt4 key购买 nike

我将 JPA2 与 Hibernate 一起使用,并尝试为我的实体引入一个公共(public)基类。到目前为止,它看起来像这样:

@MappedSuperclass
public abstract class BaseEntity {

@Id
private Long id;

@Override
public int hashCode() {
// ...
}

@Override
public boolean equals(Object obj) {
// ...
}

public Long getId() {
return this.id;
}

public void setId(Long id) {
this.id = id;
}
}

但是,对于每个表,都有一个序列 $entityname_seq 我想用作我的序列生成器。如何从我的子类中设置它?我想我需要覆盖@GeneratedValue 并使用@SequenceGenerator 创建一个新的SequenceGenerator。

最佳答案

是的,这是可能的。您可以使用 @SequenceGenerator 注释覆盖默认生成器名称。

  • 基类
    @MappedSuperclass
public abstract class PersistentEntity implements Serializable
{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "default_gen")
protected Long id = 0L;

public Long getId()
{
return id;
}

public void setId(Long id)
{
this.id = id;
}
}
  • 序列 (SQL)

    create sequence role_seq;
  • 派生类

    @Entity
@Table(name = "role")
@SequenceGenerator(name = "default_gen", sequenceName = "role_seq", allocationSize = 1)
public class Role extends PersistentEntity implements Serializable
{
private static final long serialVersionUID = 1L;

@NotNull
@Size(max = 32)
private String name;

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}
}
  • 这种方法在 Hibernate 4.1.x 中运行良好,但在 EclipseLink 2.x 中却不行。

编辑

  • 根据评论,它似乎与 EclipseLink 2.6.1-RC1 一起使用。

关于java - MappedSuperclass - 在子类中更改 SequenceGenerator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8589928/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com