How to write a query using spring jpa to fetch all rows from a database that are matching the string we pass?

huangapple go评论72阅读模式
英文:

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&lt;User,Long&gt; {

    @Query(value=&quot;select u from User u where u.firstName = %searchtext% or u.lastName= %searchtext% or u.secondName= %searchtext%&quot;)    
    Page&lt;User&gt; findByAllColumns(@Param(&quot;searchtext&quot;) 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&lt;Employee&gt; findByFirstNameIgnoreCaseContainingOrSecondNameIgnoreCaseContainingOrLastNameIgnoreCaseContaining(String firstName,String secondName,String lastName);

huangapple
  • 本文由 发表于 2020年4月10日 13:25:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/61134491.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定