Friday, June 08, 2012

Hibernate joins with Non-Primary keys


Hibernate makes it a tad difficult to do joins on Non-Primary keys. But with a little annotation trick this can be sorted out.

So let's say there is a Parent Object
Parent (PK: id, foreign key : name)

And the Child Class:
Child(PK:id, parentName)
child.parentName maps to Parent.name
and there is a ManytoOne relationship between child and Parent.

So for the domain object mapping:

@Entity
@Table(name="Parent")
public class Parent {
 @Id
    @SequenceGenerator(name = "PARENT_ID_GENERATOR", sequenceName = "PARENT_ID_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PARENT_ID_GENERATOR")
    @Column(name = "ID")
    private Long id;

    @OneToMany(mappedBy="parent")
    private  List<child> children;

}


So the parent is just like any other domain object, the key is to use the mappedBy with the OneToMany annotation.


For the child Class:

@Entity
@Table(name="Child")
public class Child{
@Id
    @SequenceGenerator(name = "CHILD_ID_GENERATOR", sequenceName = "CHILD_ID_SEQ")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CHILD_ID_GENERATOR")
    @Column(name = "ID")
    private Long id;

    @Column(name="parent_name")
    String parentName;

    @ManyToOne
    @JoinColumn(name="parent_name", referencedColumnName="name")
    Parent parent;

}

Notice how the joincolumn annotation is used. The name is the column in the child object and the referencedColumnName is the column in the parent.

That's it.
We have a join for OnetoMany Parent-&gt;Child relationship set up.</child></div>