Avoid cascade erasure JPA

1

I have the following class:

/** 
To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modelo;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;

/**
*
* @author Daniel
*/
@Entity
public class Usuario implements Serializable
{
    @Id
    private String username;
    @Lob
    private byte[] fotoperfil;
    private String nombre;
    private String apellidos;
    @ManyToOne (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Nivel nivel;
    private String email;
    private String password;
    @ManyToMany (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private final List<Usuario> amigos=new ArrayList();
    @ManyToMany (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private final List<Via> viasRealizadas=new ArrayList();
    @ManyToMany (fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private final List<PeticionAmistad> peticionesAmistad=new ArrayList();

}

If I delete a User, I want to avoid cascading the relationship data. For example, if I delete a user, I want to avoid deleting the users included in the friends list.

How can you get it?

    
asked by Daniel Muñoz Gallardo 06.12.2016 в 13:53
source

1 answer

1

You must change the value of cascade = CascadeType.ALL in this way:

@ManyToMany (fetch = FetchType.EAGER, cascade = {CascadeType.MERGE, CascadeType.PERSIST})

Inside the "{}" keys you can place the cascade you need in the relationship one by one.

The possibilities are: PERSIST, MERGE, REMOVE, REFRESH, DETACH . The PERSIST is to create (INSERT INTO), the MERGE is to modify (UPDATE) and the REMOVE is to delete (DELETE).

The REFRESH is to update the state of the entity, with the values that are in the database.

The last type DETACH I've never used it.

    
answered by 06.12.2016 / 14:58
source