2017-09-13 172 views
0

我有從數據庫中刪除實體的問題。無論我做什麼,它都不會刪除。彈簧數據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

回答

2

它看起來你的外鍵錯誤與它是根據你的代碼行鏈接客戶表:

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

所以,如果您在註釋中添加cascade = CascadeType.REMOVE,它可能會有效。但是,如果您想要刪除級聯中的所有內容(包括客戶端行),那就取決於您。如果不是,則先將該列值更新爲空。

+0

謝謝,我的壞。 – GVArt