我在Hibernate中使用JPA2,并尝试为我的实体引入一个公共基类。到目前为止,它看起来像这样:
@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中工作得很好。
编辑
- 根据评论,它似乎与EclipseLink 2.6.1-RC1一起工作。
在JPA中不能使用注释完成。注释本身不能被重写。实体从MappedSuperClass继承所有映射信息。只有两种注释可以用来重新定义从映射的superClass继承的映射:
- AttributeOverride覆盖列映射和
- AssociationOverride重写连接列/表
它们都不能帮助GeneratedValue
使用EclipseLink,您可以使用Customizer
。DescriptorCustomizer
接口定义了一种自定义jpa描述符(又名持久实体)的所有信息的方法。
public class SequenceCustomizer implements DescriptorCustomizer {
@Override
public void customize(ClassDescriptor descriptor) throws Exception {
descriptor.setSequenceNumberName(descriptor.getTableName());
}
}
和映射的父类:
@MappedSuperclass
@Customizer(SequenceCustomizer.class)
public abstract class AbstractEntity implements Serializable {
...
}
我写这个,因为它变得太不可读的评论接受的答案:
我有一个BaseEntity
,每个其他实体继承自:
BaseEntity.java:
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ID")
private Long id;
然后我有两个实体User
和Order
,都继承自BaseEntity
,同时也有@SequenceGenerator
注释:
User.java:
@SequenceGenerator(name = "SEQ_ID", sequenceName = "SEQ_USER", allocationSize = 1)
public class User extends BaseEntity { ... }
Order.java:
@SequenceGenerator(name = "SEQ_ID", sequenceName = "SEQ_ORDER", allocationSize = 1)
public class Order extends BaseEntity { ... }
它至少在H2上使用2个序列SEQ_USER
和SEQ_ORDERS
:
select SEQ_USER.nextval from dual;
select SEQ_ORDERS.nextval from dual;