Good afternoon!

I use JPA and Hibernate annotations.

There is a Parent which contains the Child collection. You must delete the Parent, but not delete it Childs.

Here is what I know about it: - cascade determines which function call will be repeated for the child. for example persist, delete, and so on. - if cascade is not specified, then nothing is called.

However, my knowledge diverges from reality. If I do not write a cascade, or if I list all operations except deletion, everything is deleted anyway. Does not help and the use of Hiberneytovskogo cascade.

Code:

@OneToMany() // @org .hibernate.annotations.Cascade( // org.hibernate.annotations.CascadeType.PERSIST // ) @Fetch(FetchMode.JOIN) private Set<Child> childs; 

, unidirectional.

Do I understand the use of cascade correctly? How to solve my problem?

  • one
    Since such a problem has arisen, all children need to be transferred to another parent. And then everything will be as it should. And leaving orphans is bad. - KoVadim
  • Why? Suppose there are a number of projects distributed among managers. When a manager leaves, it is not necessary to transfer projects to someone immediately. Maybe the project that nobody is working on is normal. - KutaBeach
  • And who prevents to create an "anonymous manager". If a person quits, then either transfer to an anonym or create a temporary phantom manager. In any case, links to projects need to be stored, and then GC will come and make them their own. :) - KoVadim
  • Well, let GC come, he will not force Hibernate to delete data from the table. And the anonymous manager is a kind of crutch and extra code. Can it be without him? The task is trivial. - KutaBeach
  • Instead of thought that the database engine itself can delete everything to maintain cascade integrity? The task is trivial, but solve it in one place. - KoVadim 2:55 pm

1 answer 1

As a result, I had some kind of glitch, apparently a really old cascade in the database. Here is such a simple design solves the problem:

 @OneToMany() // or @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) private Set<Project> actions; 

If the owner of such a collection is deleted, its objects will not be deleted, as it should be.

Following the results, I want to clarify 2 questions:

1) did I understand correctly that cascade annotations have nothing to do with database cascades and act only when called acc. im functions?

2) if so, is it possible to influence cascades in the constraints of the database through annotations?