简体   繁体   English

Hibernate 多对多映射到同一个实体单向

[英]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.如果我有 NodeRelation,我可以很容易地找到在树的不同层上重复使用的节点,并且不能安全地删除,这更难做到而不是(节点上的一对多 + FK 上的多对一) NodeRelation) 仅多对多映射。

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).我尝试了用 NodeRelation 表示的复合键映射的不同组合,但没有运气(根据 db 模式的验证没有通过)。 Please, advice me which mapping is better in this use case.请建议我在这个用例中哪个映射更好。

It is better to not use childNodes association in the Node .最好不要在Node使用childNodes关联。

It will be convenient to add id to the NodeRelation .id添加到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).您还可以向NodeRelation添加唯一约束(parent, child) (具有与@ManyToMany连接表相同的行为)。

It will need to do queries on NodeRelation table only.它只需要对NodeRelation表进行查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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