简体   繁体   中英

Hibernate many-to-many mapping to the same entity unidirectional

I have the table that represents kind of Tree node. The mapping below illustrates many-to-many mapping of node.

@Entity
public class Node {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToMany
    @JoinTable(name = "node_dependency",
            joinColumns = {@JoinColumn(name = "parent_id")},
            inverseJoinColumns = {@JoinColumn(name = "child_id")})
    private List<Node> childNodes = new ArrayList<>();
}

It works but I would like to have separate table mapping for the delete query simplicity.

@Entity
public class NodeRelation {

    @ManyToOne
    private Node parent;

    @ManyToOne
    private Node child;
}

If I have NodeRelation I can easily find nodes that re-used on different layers of the tree and cannot be safely deletes which is more difficult to do having instead of (One-to-many on Node + Many-to-One on FK in NodeRelation) only Many-to-Many mapping.

I tried different combinations of mapping with composite key that represented by NodeRelation but there is no luck (validation according db schema didn't passed). Please, advice me which mapping is better in this use case.

It is better to not use childNodes association in the Node .

It will be convenient to add id to the NodeRelation .

@Entity
public class Node {

    @Id
    @GeneratedValue
    private Long id;

}

@Entity
public class NodeRelation {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private Node parent;

    @ManyToOne
    private Node child;

}

Also you can add an unique constraint (parent, child) to NodeRelation (to have the same behavior as @ManyToMany join table has).

It will need to do queries on NodeRelation table only.

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