0

這是列表類「org.springframework.dao.DataIntegrityViolationException:無法執行語句

@Entity 
@Table(name = "list") 
public class List extends AbstractEntity { 

    @NotNull 
    @Column(name = "name") 
    private String name; 

    @Column(name = "description") 
    private String description; 

    @Column(name = "date") 
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") 
    private Date date; 

    //getters and setters 
} 

以下是執行類

@Entity 
@Table(name = "EXECUTION") 
public class Execution extends AbstractEntity { 

    @ManyToOne(targetEntity = List.class) 
    @JoinColumn(name = "list_id") 
    private List list; 

    @Column(name = "date") 
    @NotNull 
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") 
    private Date date; 
} 

以下是控制器的方法來刪除列表

@RequestMapping(value = "/{id}", method = RequestMethod.DELETE) 
@ResponseStatus(HttpStatus.NO_CONTENT) 
public void deleteList(@PathVariable("id") Long listId) { 
    List list = listRepository.findOne(listId); 

    listRepository.delete(listId); 
} 

雖然我執行上面的代碼,我得到以下錯誤

: ERROR: update or delete on table "list" violates foreign key constraint "fkmnja1nmiq9v42f0ojydccxf20" on table "execution" 

詳細信息:Key(id)=(1)仍然從表「執行」引用。

在刪除帶有特定ID的列表之前,如何刪除帶有列表ID的執行表?

任何幫助將是appreciated.Thank你

+0

有執行和列表之間沒有JPA的關係 - 增加一個關係,它會刪除 – farrellmr

+0

有一個ManyToOne執行和列表之間的關係。我對此比較陌生。你能幫我解決什麼需要做什麼 –

+0

你需要在列表中執行反向關係 - >執行刪除。作爲一個測試刪除執行,看看我的意思(應該刪除列表) – farrellmr

回答

1

你們的關係定義級聯行爲,

@Entity 
@Table(name = "EXECUTION") 
public class Execution extends AbstractEntity { 
    //add cascade , so on delete of list all the execution will also be removed 
    @ManyToOne(targetEntity = List.class, cascade = {CascadeType.ALL}) 
    @JoinColumn(name = "list_id") 
    private List list; 

    @Column(name = "date") 
    @NotNull 
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") 
    private Date date; 
} 
相關問題