开发者

Hibernate entity property defined by a query

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开发者_JAVA技巧 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
}


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜