Deleting children records with @Manytoone annotation from Spring JPA

Asked

Viewed 1,247 times

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
}

The insertion of both records works and I can book a gift. I need that when excluding a gift, the associated reserves are also excluded, but even with the mapping above and with the cascade I get the message from error saying:

Cannot delete or update a Parent Row: a Foreign key Constraint fails (presente.reserva, CONSTRAINT FKkrcm39i10icgcfw703oi79tbr FOREIGN KEY (presente_codigo) REFERENCES presente (codigo))

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

  • publish the method of exclusion of Presente.

1 answer

0


It looks like you are trying to delete a record that is related in another table. By the way your relationship is one-way, you should remove the present from the list of reservations that is associated, update this list so that it orphan before excluding the present.

To use JPA, if you change the relationship to Onetomany or create the two-way relationship to Manytoone will have the expected result. With JPA you should use all the methods clear and remove 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 using Ibernate:

@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 base 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;

 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.