【发布时间】:2011-09-16 09:43:52
【问题描述】:
我有一个实体和从该实体派生的专用类。 有什么方法(在 JPA 或 spring 中有些棘手)让 JPA 创建派生类的实例而不是实体类?
否则我需要为每个派生类创建“复制构造函数”。或者用看起来很笨重的代表替换继承。
【问题讨论】:
我有一个实体和从该实体派生的专用类。 有什么方法(在 JPA 或 spring 中有些棘手)让 JPA 创建派生类的实例而不是实体类?
否则我需要为每个派生类创建“复制构造函数”。或者用看起来很笨重的代表替换继承。
【问题讨论】:
如果您的实体有许多应以不同方式存储在数据库中的子类,您可以使用 JPA 继承支持(@Inheritance 等)。
如果您的实体只有一个子类应该始终用来代替该实体,您可以将该子类注释为@Entity,并将实体注释为@MappedSuperclass。
如果您想在不修改实体的情况下实现前面的案例,您可以使用提供商特定的解决方案。例如,在 Hibernate 中,您可以注册一个自定义 Interceptor 并覆盖其 instantiate() 方法。
【讨论】:
@Transient,不影响序列化。
如果您只想要实体的属性子集并且不想更改实体,那么我建议使用摘要样式查询。
@Entity
@Table(name="test_entity")
public class TestEntity extends BaseDomainObject<Long> {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class TestSummary {
private final Long id;
private final String name;
public TestSummary(Long id, String name) {
super();
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
然后你可以使用这样的查询:
select new TestSummary(te.id, te.name) from TestEntity te
JPA 将生成一个只加载您想要的字段的快速查询。我在显示实体列表时一直使用它。
【讨论】:
我现在使用 lomboks delegate 注释解决了它。
@Entity
public class MyEntity {
...
}
public class MyBusinessObject {
@Delegate
private MyEntity entity;
// other non persistent stuff
}
【讨论】: