具有聚合属性的 EJB3/JPA 实体
我想知道是否有一种方法可以在 One2Many 关系中获得作为多方聚合的一方的字段。
让我们看下面的例子:
@Entity
public class A {
@Id
private Long id;
@OneToMany (mappedBy="parentA")
private Collection<B> allBs;
// Here I don't know how to Map the latest B by date
private B latestB;
// Acceptable would be to have : private Date latestBDate;
}
@Entity
public class B {
@Id
private Long id;
private Date date;
@ManyToOne (targetEntity=A.class)
private A parentA;
}
我的问题是如何在 A 实体对象中映射latestB 字段而不进行任何反规范化(不使字段与触发器/侦听器保持同步)?
也许这个 问题 给出了一些答案,但实际上我不明白它是如何工作的,因为我仍然希望能够获取所有孩子的物体。
感谢您的阅读/帮助。
PS:我使用hibernate作为ORM/JPA提供者,因此如果不存在JPA解决方案,可以提供Hibernate解决方案。
PS2:或者只是告诉我我不应该这样做(当然有争论);-)
I wanted to know if there is a way to get in a One2Many relationship a field of the One side that is an aggregate of the Many side.
Let's take the following example:
@Entity
public class A {
@Id
private Long id;
@OneToMany (mappedBy="parentA")
private Collection<B> allBs;
// Here I don't know how to Map the latest B by date
private B latestB;
// Acceptable would be to have : private Date latestBDate;
}
@Entity
public class B {
@Id
private Long id;
private Date date;
@ManyToOne (targetEntity=A.class)
private A parentA;
}
My question is how can I make the mapping of the field latestB in the A entity object without doing any de-normalization (not keeping in sync the field with triggers/listeners)?
Perhaps this question gives some answers, but really I don't understand how it can work since I still want to be able to fetch all childs objects.
Thanks for reading/helping.
PS: I use hibernate as ORM/JPA provider, so an Hibernate solution can be provided if no JPA solution exists.
PS2: Or just tell me that I should not do this (with arguments of course) ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
@Formula
可以实现可接受的解决方案(即获取最新B
的Date
)。参考资料
资源
Implementing the acceptable solution (i.e. fetching a
Date
for the latestB
) would be possible using a@Formula
.References
Resources
请参阅
http://en.wikibooks.org/wiki/Java_Persistence/Relationships# Filtering.2C_Complex_Joins
基本上JPA不支持这一点,但一些JPA提供商支持。
你也可以,
- 使变量瞬态并从 OneToMany 延迟初始化它,或者只提供一个搜索 OneToMany 的 get 方法。
- 定义另一个最新的外键。
- 删除关系,只查询最新的。
See,
http://en.wikibooks.org/wiki/Java_Persistence/Relationships#Filtering.2C_Complex_Joins
Basically JPA does not support this, but some JPA providers do.
You could also,
- Make the variable transient and lazy initialize it from the OneToMany, or just provide a get method that searches the OneToMany.
- Define another foreign key to the latest.
- Remove the relationship and just query for the latest.