1

In my application I get org.hibernate.exception.ConstraintViolationException when I include 2 or more lists of the same entity(@OneToMany relations) in one class.

    @Embeddable
    data class DocPresentation(

            @OneToMany(cascade = [CascadeType.ALL])
            var billOfLadingComments: List<Comment>?,


            @OneToMany(cascade = [CascadeType.ALL])
            var invoiceComments: List<Comment>?,

            ...

    @Entity
    @Table(name = "Comment")
    data class Comment(

            @Column(name = "date")
            var date: Date?,

            @Column(name = "message")
            var message: String?,

            @Embedded
            var sender: Company?

    ) {
        constructor() : this(null, null, null)

        @Id
        @GeneratedValue
        @Column(name = "database_id")
        var databaseId: Int? = null
    }

The relation is unidirectional, so an intermediary table is created which holds the ids of the related entities. In this case it includes the id of the embedding entity of DocPresentation, and 2 colums: billOfLadingComments_database_id and invoiceComments_database_id. When I comment one of the lists the application works properly. How can I resolve the exception?

  • 1
    Have you tried to configure these two relations by JoinTable annotation? Look at -> https://stackoverflow.com/questions/5478328/jpa-jointable-annotation. – oputyk Sep 25 '19 at 10:22
  • 1
    Are you using one common JoinTable for 2 OneToMany mappings? – Martin'sRun Sep 25 '19 at 10:23
  • 1
    @oputyk that post helped, I've resolved the error due to the link you've provided. Please post the comment as an answer so I could rate it up and mark as the best answer. – Hayk Kerobyan Sep 26 '19 at 07:59
  • @Martin'sRun, yeah, I did so. Now I use different JoinTables for each List. Thanks for your comment. – Hayk Kerobyan Sep 26 '19 at 08:01

1 Answers1

0

I've solved in this way. I use 2 Join columns as there are 2 IDs in the embedding entity.

@ElementCollection
            @CollectionTable(
                    name = "docs_presentation_bill_of_lading_hashes",
                    joinColumns = [
                        JoinColumn(name = "transaction_id", referencedColumnName = "transaction_id"),
                        JoinColumn(name = "output_index", referencedColumnName = "output_index")
                    ]
            )
            @Column(name = "bill_of_lading_hash")
            var billOfLading: List<String>? = null,

            @OneToMany(cascade = [CascadeType.ALL])
            @JoinTable(
                    name = "doc_presentation_bill_of_lading_comments",
                    inverseJoinColumns = [
                        JoinColumn(name = "bill_of_lading_comment_id", referencedColumnName = "database_id")
                    ]
            )
            var billOfLadingComments: List<Comment>? = null,