Search code examples
spring-data-jpajpql

Select element by object attribute in element collection


I'm not very deep into JPA Queries and have the current situation:

@Entity(name = "ParentElement")
@Table(name = "parent_element")
data class ParentElementData(
        @Id
        @GeneratedValue
        val id: Long?,
        @ElementCollection
        var values: List<ChildElementData> = emptyList(),
)

@Entity(name = "ChildElement")
@Table(name = "child_element")
data class ChildElementData(
        @Id
        @GeneratedValue
        val id: Long?,
        @Column(nullable = false)
        val attribute: Long,
)

What I would like to achieve is getting all ParentElements where ChildElement.attribute has a specific value.

So I started with the Repository

interface ParentElementRepository : CrudRepository<ParentElementData, Long> {
   @Query("select p from ParentElement p where p.values ")
   fun findByChildAttribute(attribute: Long): List<ParentElementData> 
}

but I have no idea how to finish the query. Had a look on that: https://github.com/odrotbohm/repositories-deepdive/blob/master/src/main/java/de/olivergierke/deepdive/ProductRepository.java but doesn't work yet.

Thx


Solution

  • The query will be like:

    @Query("select p from ParentElement p JOIN p.values val where val.attribute = ?1 ")
    fun findByChildAttribute(attribute: Long): List<ParentElementData> 
    

    As you can see, the @ElementCollection works just as the @OneToMany.