简体   繁体   中英

Hibernate Unidirectional OneToMany with composite key

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, ie, a child should not reference the parent (want to omit Parent instance in the child class). Is it possible?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM