2

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?

lanoxx
  • 12,249
  • 13
  • 87
  • 142
Rams
  • 47
  • 1
  • 5

1 Answers1

4

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
wypieprz
  • 7,981
  • 4
  • 43
  • 46
  • 1
    What if I have EmbeddedId at both parent and child side(both has different columns), and I want to map OneToMany from Parent to Child. I can't use @JoinColumns as one column is not at both end. and not working with mappedBy also... any idea? – Bhaumik Thakkar Jan 28 '22 at 12:04