简体   繁体   English

一对一休眠

[英]Hibernate unidirectional one to one

I have two classes 我有两节课

class Point {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "point_id")
    private Long id;

    @Column(name = "name")
    private String name;
}
class Link {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "link_id")
    private Long id;

    @Column(name = "name")
    private String name;

    @OneToOne
    @JoinColumn(name = "fp_id")
    private Point firstPoint;

    @OneToOne
    @JoinColumn(name = "sp_id")
    private Point secondPoint;
}

If I remove Link I get constraint error. 如果删除链接,则会出现约束错误。 I want to get the following functionality: 我想获得以下功能:

  1. remove Point -> Link removed automatically 删除点->链接自动删除
  2. remove Link -> Point didn't remove automatically 删除链接->点没有自动删除

How to configure this relation? 如何配置这种关系?

UPDATE Diagram of DB 数据库更新

DB图

This doesn't look like a one-to-one association to me, since a point could have multiple incoming links. 在我看来,这似乎不是一对一的关联,因为一个点可能有多个传入链接。 It looks rather like a VIRTUAL one-to-many on the point side and two many-to-one associations on the link side. 在点侧看起来像虚拟的一对多,在链接侧看起来像是两个多对一的关联。

Now, actually mapping the one-to-many is very tricky, since it would be need to be mapped to TWO columns on the child side. 现在,实际映射一对多非常棘手,因为需要将其映射到子端的两个列。 You could fix this by having two collections on point, one for each column in link, like incoming and outgoing links, effectively turning the undirected graph into a directed graph, but that would change the logic. 您可以通过在点上设置两个集合来解决此问题,每个集合用于链接中的每一列(例如传入和传出链接),可以有效地将无向图转换为有向图,但这会改变逻辑。

A simple mapping with two many-to-one properties would be easiest to implement. 具有两个多对一属性的简单映射将最容易实现。 Deleting the links should then be done by the application, right before deleting a point, by using a hql batch delete operation: delete from link where firstPoint = :point or secondPoint = :point. 然后,应用程序应该在删除点之前,通过使用hql批处理删除操作删除链接:从其中firstPoint =:point或secondPoint =:point的链接中删除。

If you really require hibernate to do the deletion for you, I would suggest to create two collections with cascade=delete. 如果您确实需要休眠来为您执行删除操作,我建议您创建两个带有层叠=删除的集合。

尝试这个

@OneToOne(cascade = CascadeType.REMOVE)

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

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