我将JPA2与Hibernate结合使用,并尝试为我的实体引入一个通用的基类。到目前为止看起来像这样:
@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;
}
}
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;
}
}
编辑