Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate @JoinFormula

Tags:

hibernate

I have two entities A and B.

 public class A{

    @Id
    @GeneratedValue
    private Integer id;

    private String uuid;

    ...
  }

The UUID is given externally; ID can be seen as version.

Now, I'd like to reference A in B such that I have the uuid stored in B and automatically select the A with the according uuid and the highest id.

What I tried is:

public class B{
      @Id 
      @GeneratedValue
      private Integer id;

      private String uuidOfA;

      @ManyToOne
      @JoinFormula(value="SELECT a.id FROM A a WHERE v.uuid = uuidOfA AND v.id = (SELECT max(x.id) FROM A x WHERE x.uuid = v.uuid)", referencedColumnName="id")
      private A a; 

      ...        
}

This will create a column containing A's id in B and throws an exception if I try to persist an object. I've also tried @JoinColumnsOrFormulas without luck.

Can someone give me a hint on how to do this (in Hibernate 3.5 btw)?

Thanks!

like image 546
Simon Avatar asked Jun 11 '12 12:06

Simon


1 Answers

The following works:

@ManyToOne
@JoinColumnsOrFormulas({
  @JoinColumnOrFormula(formula=@JoinFormula(value="(SELECT a.id FROM A a WHERE a.uuid = uuid)", referencedColumnName="id")),
  @JoinColumnOrFormula(column = @JoinColumn("uuidOfA", referencedColumnName="uuid"))
})
private A a;
like image 75
Simon Avatar answered Oct 21 '22 03:10

Simon