简体   繁体   中英

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.

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)

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