0

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

Diagram of DB

avfrolov
  • 366
  • 1
  • 3
  • 11

2 Answers2

1

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.

Maarten Winkels
  • 2,407
  • 16
  • 15
  • Thanks for your reply! You are right, it doesn't look as one-to-one association, but I don't know how to call this association. Unfortunately, I don't want have references to Link in entity Point. I can map points as id's in Link and take a manual control for CRUD operations... But I want use Hibernate capabilities – avfrolov Aug 06 '14 at 07:20
  • See this question: http://stackoverflow.com/questions/1715146/how-to-define-an-inverse-cascade-delete-on-a-many-to-one-mapping-in-hibernate. What you want is not possible. You would be able to do it with DB specific stuff, like her: http://stackoverflow.com/questions/1137320/understanding-update-and-delete-rules-for-relationships-in-ssms-2008. – Maarten Winkels Aug 06 '14 at 07:35
0

Try this

@OneToOne(cascade = CascadeType.REMOVE)
sanj
  • 381
  • 3
  • 3