Deleting child records with Spring JPA @ManyToOne annotation

1

I have the classes Presente and Reserva , as below:

@Entity 
public class Presente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    private String nome;
    //getters e setter omitidos
}
@Entity
public class Reserva {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    private String email;

    @ManyToOne(cascade = CascadeType.REMOVE)
    private Presente presente;
    //getters e setter omitidos
}

Inserting both records works and I can book this one. I need to exclude a present, the associated reservations are also deleted, but even with the mapping above and with cascade I get the error message saying:

  

Can not delete or update a parent row: a foreign key constraint fails ( presente . reserva , CONSTRAINT FKkrcm39i10icgcfw703oi79tbr FOREIGN KEY ( presente_codigo ) REFERENCES presente

I know the message is due to bank integrity, but should codigo not treat this behavior by deleting the reservations before deleting the present? What do I need to change?

    
asked by anonymous 28.12.2016 / 23:11

1 answer

0

It seems like you are trying to delete a record that is listed in another table. In the form of your relationship being unidirectional, you must remove the present from the list of reservations that is associated, update this list so that it is orfam before deleting present.

To use JPA, if you change the relationship to OneToMany or create the bidirectional relationship for ManyToOne will have the expected result. With JPA you should make use of the clear and remove methods of EntityManager.

@Entity 
public class Presente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    private String nome;

   @OneToMany(mappedBy = "presente", cascade = CascadeType.REMOVE)
   private Set<Reservas> reserva;
}

If you use hibernate:

@Entity 
public class Presente {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    private String nome;

    @OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="presente", orphanRemoval=true)
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    private List<Reserva> reservas;
}

If you allow hibernate to manage the schema of your database you can use

@Entity
public class Reserva {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long codigo;

    private String email;

    @ManyToOne
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Presente presente;

 }
    
29.12.2016 / 21:39