15

I am using Spring Data JPA.

I an entity like this

public class A {

    @CollectionTable(name = "B_ITEMS", joinColumns = @JoinColumn(name = "B_ID"))
    @ElementCollection
    private List<B> bs;

}

And an Embedded class

@Embeddable
public class B { 

private String prop1


private String prop2


private String prop3

}

How do I search entity A using the contents @ElementCollection B?

And here's my repository Spring Data JPA Repositry

public interface ARepo extends PagingAndSortingRepository<Clinic, Long> {

}

What Query method name is applicable for my use case?

0

4 Answers 4

4

You seem to be asking for a basic IN query in Spring Data - findBybsIn(List<B> bs)

Sign up to request clarification or add additional context in comments.

Comments

4
+25

@ElementCollection is just a simple way to map a @OneToMany relation.

As such you can join them as usual:

public interface ARepo extends PagingAndSortingRepository<A, Long> {
    @Query("select a from A a join a.bs b where b.prop1 = :prop1 and ...")
    A findByProps(@Param("prop1") String prop1)
}

Comments

2

Instead of using @Query like in @Zeromus answer you can also define it by method name (findByElementCollectionProperty_NestedProperty):

public interface ARepo extends JPARepository<A,Long> {

    List<A> findByBs_Prop1(String prop1);
}

More information how SpringData resolves nested Properties can be found under:

Query Property Expressions

1 Comment

how would this method look if Bs were not a collection of embeddables but a collection of simple Strings instead? Say, I want to know if a particular string argument matches with a string in the elementcollection. Would the method then look like this: findByBsIn(String arg) or should it be different?
1

An approach could be to search a list of A objects for all the properties of B object. That means use filters for prop1, prop2 and prop3 together.

public interface ARepo extends PagingAndSortingRepository<Clinic, Long> {
    List<A> findByBsProp1AndBsProp2AndBsProp3(String prop1, String prop2, String prop3); 
}

3 Comments

this is a findby based on all the 3 properties of @Embeddable object. So if i need to search list of A for a specific object B, i can use this method and filter for all the properties, that means filter for the object itself.
While this code could solve the problem, it is best to add elaboration and explain how it works for people who might not understand this piece of code.
thanks for your feedback. Also if i already explained in comments, i tried to improve the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.