I would like to create an optional ManyToOne association between two entities based on whether entity1.name equals entity2.nameOf1, but I don’t want to have to maintain this relationship in my service layer by adding, removing, fetching objets, I just want that when I get an entity2, either hibernate adds a left join entity1 e1 on e1.name = e2.nameOf1 to the select query or that it waits for a call entity2.getEntity1() to query for entity1 with a where e1.name == ? with nameOf1 as argument. I have tried so far by using @JoinFormula annotation but there is very little documentation about it. I’m using hibernate version 3.5.6 with annotations.
@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...
}
I think you should just use a query to do that:
If you really want to go this road, a simple ManyToOne with a JoinColumn should be sufficient. You need to make it non-insertable and non-updatable, though: