2
votes

I wanted to frame Hibernate OneToMany relationship where Parent has a composite primary key and Child has a primary key (hibernate-auto generated). Below is my working sample code :

class Parent{

    @EmbeddedId
    private ParentPk parentPk;

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

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

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

    //--setters and getters
}

@Embeddable
public class ParentPk {

    private Long parentId;

    private BigDecimal version;

    //..setters and getters
}

class ChildType1{
    @Id
    private Long childId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumns({ @JoinColumn(name = "parentId"),
            @JoinColumn(name = "version") })
    private Parent parent;

    //..other fields and setters and getters
}

//--ChildType2 and ChildType3 like above

But now I wanted to model above as OneToMany unidirectional relationship, i.e., a child should not reference the parent (want to omit Parent instance in the child class). Is it possible?

1
Yes, it's possible. Put the JoinColumns annotation on the List in the parent class. - JB Nizet

1 Answers

4
votes

An example approach:

@Entity
class Parent {
    @EmbeddedId
    private ParentPk parentPk;

    @OneToMany
    @JoinColumns({ 
        @JoinColumn(name = "parentId", referencedColumnName = "parentId"), 
        @JoinColumn(name = "version", referencedColumnName = "version")
    })
    private List<ChildType1> children1;

    // exactly the same annotations as for children1
    private List<ChildType2> children2;

    // exactly the same annotations as for children1
    private List<ChildType3> children3;

    //..other fields and setters and getters
}

@Entity
class ChildType1 {
    @Id
    private Long childId;

    //..other fields and setters and getters
}

//--ChildType2 and ChildType3 like above