3

I wanted to perform the Spring JPA repository where wanted to apply the and operation among 2 columns where one column cloud have multiple values in it.

SQL query for the same:

select * from table_name where col1='col1_val' and col2 IN ('col2_val_a','col2_val_b','col2_val_c');

I know that for and operation I can extend the JpaRepository and create the method with like this for:

List<MyPoJoObject> findByCol1AndCol2(String col1_val,String col2_val);

and for IN operation we can use : findByCol2In(Collection<String> col2_val)

But i did not know how i can club both the mentioned JPA default method into one, as per my sql statement mentioned before.

3 Answers 3

3

You can use the following method named:

List<MyPoJoObject> findByCol1AndCol2In(String col1_val, Collection<String> col2_val);

On this link repository-query-keywords you can find repository query keywords that you can use and combine them as well.

1

You can certainly combined both into one method.

List<MyPoJoObject> findByCol1AndCol2In(String col1_val,String[] col2_val);

Try this. I am not sure if it will accept Collection<String>. I will try that and update the answer.

HTH.

0
0

If you want to perform this logic for more than two columns then your method name becomes verbose.

Instead of stuck with Spring naming why can't you write your own JPA query.

Example:

@Query("select pojo from MyPoJoObject as pojo where pojo.col1 = :col1_val and pojo.col2 in :col2_val")
List<MyPoJoObject> findByColumns(String col1_val, List<String> col2_val);
3
  • We can use the spring default operators as mentioned in the comment above. Thanks for your comment. Commented Sep 18, 2019 at 4:39
  • @GnanaJeyam I avoid writing my own JPA query and use the "repository named query" method. Why? Because errors in writing a JPA query are not surfaced until runtime. However, warnings with a "repository named query" occur at compile time. So, for those of us who want the compiler to remove as many issues prior to run time as possible, it behooves us to bias towards the "repository named query" option as much as is possible. Commented Jan 31 at 17:32
  • 1
    @chaotic3quilibrium Yes it is better to follow named query to avoid runtime syntax issues and it will also provide you a better performance.
    – GnanaJeyam
    Commented Feb 1 at 7:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.