Kotlin + Spring Data Exception (Constraint violation)

303 Views Asked by At

I'm coding a quite simple REST API using Spring Boot/Spring Data with Kotlin. The basic idea is that a Person can have many books. So I want to make a CRUD operation where I want to create, consult, etc. I'm using the H2 database and I'm already subscribing 4 people with 2 books for each one. I've been able to retrieve all the people stored up in the database and I can also retrieve one single person from the database by the methods findAll() and findById(id) but when I try to save(), delete() or update() I'm facing a ConstraintViolationException. I've made the @ManyToOne in the PersonEntity class and have the @OneToMany in the BookEntity class with the @JoinColumn annotation according to the tutorials but I'm kinda lost in this part...
I'm having this error when trying to delete a specific person that is stored up in the database. Here are the error and the code. I really appreciate if you guys have any tip for me regarding this. Thank you!

-> org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: "CONSTRAINT_8C: PUBLIC.PERSON FOREIGN KEY(BOOK_ID) REFERENCES PUBLIC.BOOK(BOOK_ID) (1)"; SQL statement:
delete from book where book_id=? [23503-200]

@Entity
@Table(name = "PERSON")
class PersonEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val person_id : Long = 0L

    @Column(name="name", nullable = false)
    var name : String = ""

    @Column(name="email", nullable = false)
    var email : String = ""

    @OneToMany(cascade = [(CascadeType.ALL)], fetch = FetchType.LAZY, mappedBy = "person_id", orphanRemoval = true)
    var books : List<BookEntity?> = ArrayList()
}

----

@Entity
@Table(name = "BOOK")
class BookEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var book_id : Long = 0L

    @Column(name="title", nullable = false)
    var title : String = ""

    @Column(name="author", nullable = false)
    var author : String = ""

    @Column(name="publishing_company", nullable = false)
    var publishingCompany : String = ""

    @Column(name="publishing_year", nullable = false)
    var publishingYear : String = ""

    @Column(name="location", nullable = false)
    var location : String = ""

    @ManyToOne(fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "person_id", nullable = false)
    @JsonIgnore
    private var person_id : PersonEntity? = PersonEntity()
}

--
1

There are 1 best solutions below

1
On

You have cascade type correctly In your code should work. Try add below things on both side.

cascade = [(CascadeType.REMOVE)]