1

Sorry for the long explanation in advance, I have been searching for similar issues to no avail.

I have two Tables, let's call them Table A and Table B

A has a foreign key Association with B i.e. Table B's tB_id value is a foreign key in Table A

Code Reference

TableA

@Entity
@Table(name = "tableA")
data class TableA(
    @Id @Column(name = "id") val id: String,
    @Column(name = "name") val name: String,
    @ManyToOne(cascade = [CascadeType.ALL])
    @JoinColumn(name = "tB_id", referencedColumnName = "tB_id", nullable = false)
    val table2: Table2,
)

TableB

@Entity
@Table(name = "tableB")
data class TableB(
    @Id @Column(name = "tB_id") val tB_id: String,
    @Column(name = "name") val name: String,
)

Issue

I tried creating a list of objects of TableA and saving them

val x = listOf(TableA("id1","name1",TableB("idB1","nameB1"),
TableA("id2","name2",TableB("idB1","nameB1"))
tableARepo.saveAll(x)

It throws an error saying A different object with the same identifier value was already associated with the session since it does not understand that both the objects are the same (atleast data wise)

What works

If I extract the TableB object out and pass the reference instead, the code (test) works I can't use it since this is a list of data sent by users that is converted to a list of TableA objects

Question

  • Is there a way for me to save the object using saveAll() in the current structure ?
  • Is there a another alternative where I don't have to destructure the input List ?

0 Answers0