0

This is the list class

@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
}

Following is the execution class

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

Following is the controller method to delete list

@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);
}

While I execute the above code I get the following error

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

Detail: Key (id)=(1) is still referenced from table "execution".

How can I delete the execution table with list id's before deleting the list table with a particular id?

Any help will be appreciated.Thank you

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
A.S
  • 798
  • 1
  • 10
  • 32

1 Answers1

1

Define cascade behavior on your relationship,

@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;
}
ScanQR
  • 3,740
  • 1
  • 13
  • 30