micronaut-data icon indicating copy to clipboard operation
micronaut-data copied to clipboard

@Join annotation does not fetch entity for findAll methods from CrudRepository

Open wykingvl opened this issue 3 years ago • 4 comments
trafficstars

Expected Behavior

I am trying to create a simple structure with 2 entities, a child and a parent and try to eagerly fetch the child in my findAll queries and avoid an n+1 problem. I am trying to accomplish this using the @Join annotation which seems to work for my findById method. Could anyone help?

Actual Behaviour

The child is fetched when calling the findById method, but when calling findAll the child is not fetched.

Steps To Reproduce

@MappedEntity(value = "parent")
data class Parent(
    @field:Id
    @GeneratedValue(GeneratedValue.Type.UUID)
    var id: UUID? = null,
   
    @JoinColumn(name = "parent_id")
    @Relation(Relation.Kind.MANY_TO_ONE, cascade = [Relation.Cascade.ALL])
    var child: Child?
)
@MappedEntity(value = "child")
data class Child (
    @field:Id
    @GeneratedValue(GeneratedValue.Type.UUID)
    var id: UUID? = null,

    var description: String,

    @DateCreated
    var createdAt: Instant,
    @DateUpdated
    var updatedAt: Instant,
)
@JdbcRepository
@Requires(env = ["db"])
@Transactional(Transactional.TxType.MANDATORY)
@Join(value = "parent")
interface ParentRepository : CrudRepository<Parent, UUID>, JpaSpecificationExecutor<Parent> {

    override fun findById(id: UUID): Optional<Parent>
    override fun findAll(spec: PredicateSpecification<Overdraft>?): MutableList<Parent>
}

Environment Information

Kotlin java 17

Example Application

No response

Version

3.5.1

wykingvl avatar Jun 20 '22 08:06 wykingvl

Criteria don't apply joins defined by the Join annotation. You need to do it manually for now.

dstepanov avatar Jun 20 '22 08:06 dstepanov

Thanks @dstepanov for the quick reply. Which is the most elegant way I can do it right now?

wykingvl avatar Jun 21 '22 06:06 wykingvl

Just do the join in the criteria: root.join("others"), more about the spec https://jakarta.ee/specifications/persistence/3.0/jakarta-persistence-spec-3.0.html#a6925

dstepanov avatar Jun 21 '22 10:06 dstepanov

This looks like duplicate of #1690

radovanradic avatar Aug 30 '22 12:08 radovanradic

Closing as duplicate

dstepanov avatar Sep 08 '23 07:09 dstepanov