I have a sql statement as below and want to convert it to JPA
SELECT * FROM employee
where user_id in ('id1', 'id2', 'id3')
AND (
first_name like '%name1%' OR last_name like '%name1%'
OR
first_name like '%name2%' OR last_name like '%name2%'
)
ORDER BY user_id ASC;
Input parameter
userIdList - a list of string to exact match user_id of size [1,100]
nameList - a list of string to like-wise match first_name or last_name of size [1,100] in character [A-Za-z0-9-_ ]
example for name list: ['Joe', 'Peter', 'White', 'X Y']
I have no idea about how to handle the List of like part and the closest I have is without the list of like
@Modifying
@Query(value = "select * from employee where user_id IN :ids ORDER BY user_id",
nativeQuery = true)
List<UserGroupTable> findAllByUserIdList(@Param("ids") List<String> userIdList);
In clause reference: %Like% Query in spring JpaRepository
Assuming the intention is for name1
and name2
to also be parameters, you only need to finish out your JPA query:
select *
from employee
where user_id IN :ids and (
first_name like :name1 or last_name like :name1 or
first_name like :name2 or last_name like :name2)
order by user_id
Your updated Java method:
@Modifying
@Query(value = "select * from employee where user_id IN :ids and (first_name like :name1 or last_name like :name1 or first_name like :name2 or last_name like :name2) order by user_id",
nativeQuery = true)
List<UserGroupTable> findAllByUserIdList(@Param("ids") List<String> userIdList, @Param("name1") String name1, @Param("name2") String name2);
Note carefully here that you bind to :name1
and :name2
the actual wildcard expression. Eg for a name of John Doe
, you would bind %John%
and %Doe%
to the two placeholders.
A regex query could be one way to achieve this, as described here: Searching multiple colums with a Contains query with a list of Items in Spring-Data JPA
Sample for MariaDB
/ MySQL
:
@Query(nativeQuery = true, value = "SELECT * FROM my_entity WHERE "
+ "first_name REGEXP CONCAT_WS('|', :nameslist) " + "OR "
+ "last_name REGEXP CONCAT_WS('|', :nameslist) ")
List<MyEntity> findByNames( // (method name does not matter)
@Param("nameslist") Collection<String> nameslist);
( CONCAT_WS
joins the provided list, eg ('val1', 'val2', 'val3')
to the regex 'val1|val2|val3'
, which would match eg 'complete val2
xxx'.)
Note that the exact REGEXP / CONCAT_WS functions depend on the used DB.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.