如何在hibernate中基于属性比较关联两个实体?

时间:2012-05-31 15:40:09

标签: hibernate hibernate-mapping

我想根据entity1.name equals entity2.nameOf1是否在两个实体之间创建一个可选的ManyToOne关联,但我不想通过添加,删除,获取objets来维护我的服务层中的这种关系,我只是我希望当我得到一个entity2时,要么hibernate在select查询中添加left join entity1 e1 on e1.name = e2.nameOf1,要么等待调用entity2.getEntity1()来查询具有where e1.name == ?并且nameOf1为参数的entity1。到目前为止,我已经尝试过使用@JoinFormula注释,但是关于它的文档很少。我正在使用带有注释的hibernate 3.5.6版。

@Entity
public class Entity1 {
   @Id
   @GeneratedValue
   private Long id;
   @Column(unique = true)
   private String name;

   ...getter&setters...
}
@Entity
public class Entity2 {
   @Id
   @GeneratedValue
   private Long id;

   private String someProp;
   private String nameOf1;

   @ManyToOne(optional = true)
   // How to join them? this doesn't work
   // @JoinColumnsOrFormulas({ @JoinColumnOrFormula(formula = 
   //      @JoinFormula(value = "nameOf1", referencedColumnName = "name")) })
   // neither does
   // @JoinColumnsOrFormulas({ @JoinColumnOrFormula(column =
   //      @JoinColumn(name = "nameOf1", referencedColumnName = "name", 
   //          insertable = false, updatable = false, nullable = true)) })
   //@Fetch(FetchMode.JOIN)
   private Entity1 entity1;

   ...getter and setters...
}

1 个答案:

答案 0 :(得分:1)

我认为您应该使用查询来执行此操作:

select e1 from Entity1 e1 where e1.name = :name

如果你真的想走这条路,那么带有JoinColumn的简单ManyToOne就足够了。但是,您需要使其不可插入且不可更新:

@ManyToOne(optional = true)
@JoinColumn(name = "nameOf1", referencedColumnName = "name", 
            insertable = false, updatable = false)
private Entity1 entity1;