由查询定义的 Hibernate 实体属性
我尝试用 Java 和 Hibernate 实现文档修改跟踪系统。文档的每个 mod 都保存有作者和时间戳。要获取文档的创建者,我需要获取最早的 mod。这里是:
@Entity
@Table(name="Modifications")
public class Modification
{
String autor;
Date dateTime;
Document document;
@ManyToOne
public Document getDocument() {
...
}
// Author of this mod
@Column(name="Autor")
public String getAutor() {
...
}
// and other properties
}
@Entity
@Table(name="Documents")
public class Document
{
private List<Modification> modifications;
@OneToMany(mappedBy="document")
public List<Modification> getModifications() {
...
}
// this property is question about. How should I implement this with hibernate?
//I don't want to store "autor" field in entity,
//it should be determined with query to modifications table.
// But I can't find any example of defining properties this way...
// So I need your advices :)
public String getAutor() {
...
}
// other properties
}
I try to implement document modifications tracking system with Java and Hibernate. Every mod to document is saved with autor and timestamp. To get the creator of document I need to get earliest mod. Here it is:
@Entity
@Table(name="Modifications")
public class Modification
{
String autor;
Date dateTime;
Document document;
@ManyToOne
public Document getDocument() {
...
}
// Author of this mod
@Column(name="Autor")
public String getAutor() {
...
}
// and other properties
}
@Entity
@Table(name="Documents")
public class Document
{
private List<Modification> modifications;
@OneToMany(mappedBy="document")
public List<Modification> getModifications() {
...
}
// this property is question about. How should I implement this with hibernate?
//I don't want to store "autor" field in entity,
//it should be determined with query to modifications table.
// But I can't find any example of defining properties this way...
// So I need your advices :)
public String getAutor() {
...
}
// other properties
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不会在 getAutor() 方法中实现查询,至少不会在实体中实现。
IMO 实体不应自行执行查询。
那么为什么不在某些服务/DAO 中提供一种方法来根据需要提供作者呢?
或者,您可能想在文档中为作者创建一个临时字段,并让它由 dao 填充。这样,您只需加载作者一次并多次访问该信息。
I'd not implement a query in the
getAutor()
method, at least not in the entity.IMO entites should not execute queries themselves.
So why don't you just provide a method in some service/DAO that provides the author as needed?
Alternatively you might want to make a transient field for the author in the document and let it fill by the dao. This way you'd have to load the author only once and access the information multiple times.
我猜你正在尝试通过注释来做到这一点。您可以尝试在修改列表上设置 @OrderBy 并让 getAutor() 函数检索第一个(或最后一个)实体。
尽管我更喜欢托马斯的方法论,因为它可以更好地分离出这种逻辑。
I'm guessing you're trying to do it through annotations. You can try to set @OrderBy on your list of Modifications and have your getAutor() function retrieve the first (or last) entity.
Although I like Thomas' methodology better as to better separate out that logic.