简体   繁体   English

不区分大小写的查询,使用 Hibernate 和 mysql 返回区分大小写的数据

[英]Case insensitive query that returns case sensitive data with Hibernate and mysql

In my REST-api I am using Spring Boot with a mysql database.在我的 REST-api 中,我使用 Spring Boot 和 mysql 数据库。 One of my entities has a string name as its primary key.我的一个实体有一个字符串名称作为其主键。 When I query the corresponding table, the query is case insensitive per default.当我查询相应的表时,默认情况下查询不区分大小写。 That's all good, but mysql returns the primary key cased exactly like typed in the query.这一切都很好,但是 mysql 返回主键的大小写与查询中键入的完全一样。 For example:例如:

findOne("John") returns:
{"name": "John",
 "age": 21}

and

findOne("joHn") returns:
{"name": "joHn",
 "age": 21}

Is there a way to query query the database case insensitively, and have it return the primary key exactly as it reads in the database?有没有办法不区分大小写地查询数据库,并让它完全按照它在数据库中读取的方式返回主键? So that, for example, findOne("JOHN") would return {"name": "John"}.因此,例如 findOne("JOHN") 将返回 {"name": "John"}。

I've seen a similar question posted here before, where the solution was just to use toLowerCase(), but obviously that doesn't cut it here.我之前在这里看到过一个类似的问题,解决方案只是使用 toLowerCase(),但显然这并不能解决问题。

In this scenario, you should try using the IgnoreCase for Case Insensitive Queries.在这种情况下,您应该尝试将IgnoreCase用于不区分大小写的查询。

Now, suppose we want to perform a case-insensitive search to find all passengers with a given firstName.现在,假设我们要执行不区分大小写的搜索以查找具有给定名字的所有乘客。

To do so, we'll define our PassengerRepository as:为此,我们将PassengerRepository定义为:

public interface PassengerRepository extends JpaRepository<Passenger, Long> {
    List<Passenger> findByFirstNameIgnoreCase(String firstName);
}

Here, the IgnoreCase keyword ensures that the query matches are case insensitive.在这里,IgnoreCase 关键字确保查询匹配不区分大小写。

Refer the following link for more details :: https://www.baeldung.com/spring-data-case-insensitive-queries有关更多详细信息,请参阅以下链接 :: https://www.baeldung.com/spring-data-case-insensitive-queries

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM