英文:
How to write a query using spring jpa to fetch all rows from a database that are matching the string we pass?
问题
你好,我刚接触 Spring Boot。我有一张表,其中有以下属性:id、firstName、secondName、lastName。
现在我需要编写一个查询(在 Repository 中),以查找所有在我的表中,其 firstName、secondName 或 lastName 与我传入的字符串匹配的行。
例如:如果我传入 'foo',它应该搜索所有三个列,并返回那些在任何一个列中包含 'foo' 的行(这是模式匹配)。
我应该如何做呢?提前谢谢。
英文:
Hi I am new to spring boot. I have a table having the following attributes: id,firstName,secondName,lastName.
Now I need to write a query (in repository), to find all those rows in my table whose firstName or secondName or lastName matches with the string I am passing.
eg: if I am passing 'foo' then it should search all the three columns and return those rows having 'foo' in any of them(this is pattern matching).
How can I do that? Thanks in advance.
答案1
得分: 1
你可以像这样在多列上使用 Like
查询:
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
@Query(value = "select u from User u where u.firstName like %searchtext% or u.lastName like %searchtext% or u.secondName like %searchtext%")
Page<User> findByAllColumns(@Param("searchtext") String searchtext, Pageable pageable);
}
英文:
You can use Like
query on multiple column like this way
public interface UserRepository extends PagingAndSortingRepository<User,Long> {
@Query(value="select u from User u where u.firstName = %searchtext% or u.lastName= %searchtext% or u.secondName= %searchtext%")
Page<User> findByAllColumns(@Param("searchtext") String searchtext, Pageable pageable);
}
答案2
得分: 0
你可以尝试以下代码:
public List<Employee> findByFirstNameIgnoreCaseContainingOrSecondNameIgnoreCaseContainingOrLastNameIgnoreCaseContaining(String firstName, String secondName, String lastName);
英文:
you can try with the below code
public List<Employee> findByFirstNameIgnoreCaseContainingOrSecondNameIgnoreCaseContainingOrLastNameIgnoreCaseContaining(String firstName,String secondName,String lastName);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论