I'm italian and i apologize for my english.
I have two POJO classes that rappresents a parent and a child table in my Db.
Parent. Persona.java
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "nome", length = 30, nullable = false)
private String nome;
@Column(name = "cognome", length = 30, nullable = false)
private String cognome;
@Column(name = "eta")
private int eta;
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REFRESH}, mappedBy = "persona", orphanRemoval = false)
@Column(nullable = true)
private List<Telefono> numeriDiTelefono;
// Others getters and setters
Child. Telefono.java
@Id
@Column(name = "numero_telefono")
private String numeroDiTelefono;
@Column(name = "tipo")
private String tipo;
@ManyToOne(cascade = {CascadeType.REMOVE, CascadeType.PERSIST })
@JoinColumn(name = "persona_id", nullable = true)
private Persona persona;
// Others getters and setters
I have used annotations for mapping those classes in database.
When i try to delete a Persona from the database, hibernate delete the associated Telefono with that Persona, I don't want it. I would that the child references to has a null value in the field persona_id in the Telefono table, how to obtaining that results? What annotations shoulds I used? Thanks for everyone.
JPA is not magic.
As @Andy Dufresne suggested, remove the CascadeType.REMOVE
annotation. Then you have to set Persona
to null
in the Telefono
, and clear the Telefono
collection of the Persona
before removing the Persona
from the persistence context. So you have to remove all associations.
You can even combine this with the @PreRemove
annotation.