1

I have a problem with deleting entity from database. Whatever I do anyway it doesn't delete.

Driver class

@Entity
@Table(name = "drivers")
public class Driver {

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

    @OneToMany(mappedBy = "driver", fetch = FetchType.EAGER)
    @JsonSerialize(using = RatingsSerializer.class)
    private List<Rating> ratings;

    // other fields. Getters and Setters...
}

Rating class

@Entity
@Table(name = "ratings")
@JsonDeserialize(using = RatingDeserializer.class)
public class Rating {

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

    @ManyToOne
    @JoinColumn(name = "driver_id")
    private Driver driver;

    @ManyToOne
    @JoinColumn(name = "client_id")
    private Client client;
    private int mark;
    private Date createdAt;

    //Getters and Setters ...
}

First one what I do is annotate ratings with @OneToMany(mappedBy = "driver", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.REMOVE) and when call driverRepository.delete(driver) it throws:

org.postgresql.util.PSQLException: ERROR: update or delete on table "drivers" violates foreign key constraint "fk3raf3d9ucm571r485t8e7ew83" on table "ratings"

Ok, choose another way. Try to delete each rating object using ratingRepository, but never happens, it just iterate thorough each rating item and throw again error

org.postgresql.util.PSQLException

Next step was to set for each rating item Client and Driver to null. Now driver entity is deleted from database but rating entity remain in database. What happens?

Spring Data JPA version: 1.5.7

1 Answer 1

2

It looks that your Foreign Key error is related to Client table which is linked according to your code line:

@ManyToOne
@JoinColumn(name = "client_id")
private Client client;

So, if you add cascade = CascadeType.REMOVE within the annotation, it may works. But, that' up to you if you want to delete everything on cascade including Client row. If not, then update that column value first to null.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.