弹簧数据JPA不删除实体
问题描述:
我有从数据库中删除实体的问题。无论我做什么,它都不会删除。弹簧数据JPA不删除实体
Driver类
@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...
}
评级类
@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 ...
}
首先一个我做的是注释ratings
与@OneToMany(mappedBy = "driver", fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.REMOVE)
当呼叫driverRepository.delete(driver)
它抛出:
org.postgresql.util.PSQLException: ERROR: update or delete on table "drivers" violates foreign key constraint "fk3raf3d9ucm571r485t8e7ew83" on table "ratings"
好的,选择另一种方式。尝试删除使用ratingRepository
每个等级的对象,但从未发生过,它只是重复深入每个级别项,并抛出再次出错
org.postgresql.util.PSQLException
下一步是为每个级别项客户和驱动到空集。现在驱动程序实体从数据库中删除,但评级实体保留在数据库中 会发生什么?
春数据JPA版本:1.5.7
答
它看起来你的外键错误与它是根据你的代码行链接客户表:
@ManyToOne
@JoinColumn(name = "client_id")
private Client client;
所以,如果您在注释中添加cascade = CascadeType.REMOVE,它可能会有效。但是,如果您想要删除级联中的所有内容(包括客户端行),那就取决于您。如果不是,则先将该列值更新为空。
谢谢,我的坏。 – GVArt