0

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

Kai
  • 2,145
  • 1
  • 20
  • 35
  • Are you doing this inside one unit of work? Or do you load the entities in one UoW and then save them in a different one? I'm also confused about your mention of lazy entities, but the mapping has `fetch=EAGER`. Also a mini note: spring-data (and most of spring) provides very leaky abstractions, so you need to know what spring is doing (aka going under the hood and looking at their code) if you want to understand how your app will behave. – Augusto Oct 04 '22 at 16:43
  • within one transaction boundary, yes. the holding entity and its collection are loaded. I create a reference entity and add it to the collection. Only when saving the holding entity, hibernate loads the referenced entity first, unnecessarily though – Kai Oct 04 '22 at 18:34

1 Answers1

0

This is simply an optimization that Hibernate ORM didn't implement yet. Please create an issue in the issue tracker(https://hibernate.atlassian.net) with a test case(https://github.com/hibernate/hibernate-test-case-templates/blob/master/orm/hibernate-orm-5/src/test/java/org/hibernate/bugs/JPAUnitTestCase.java) that reproduces the issue.

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58