I am using Spring Data JPA and it allows to create a lazy loaded entities using the getById call. These entities are not queried from the database unless access to it is happening.
I now want to add one of those lazy entities to the many to many relationship of a loaded entity. I assumed that when saving that entity this should result in a single SQL insert statement for the cross reference table, as all that is required is the ID of both entities, and the lazy entity should provide that id. But instead I see another query where the full entity is queried first.
The entity relationship looks like this:
@ManyToMany(fetch = FetchType.EAGER, targetEntity = SecondEntity::class)
@JoinTable(
name = "some_join_table",
joinColumns = [JoinColumn(name = "first_table_id", referencedColumnName = "id")],
inverseJoinColumns = [JoinColumn(name = "second_table_id", referencedColumnName = "id")]
)
var relatedEntities = mutableListOf<SecondEntity>()
How can I avoid that loading query on the inserted entity reference?
JPA save "new" Entity with reference to an existing Entity using only it's id? was not applicable here.
Spring Data JPA 2.6.8, Hibernate 5.6.x