java - Spring data JPA exists By Field在MySQL中不区分大小写,如何让它区分大小写

标签 java mysql spring jpa spring-data-jpa

ClientsRepository 类

public interface ClientsRepository extends JpaRepository<ClientsEntity, Long> {

    boolean existsByClientId(String clientId);

}

客户实体类

@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "clients")
public class ClientsEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    private String clientId;

}

客户表
|编号 | client_id | |--------------------|------------------| | 1 |美国广播公司 | |--------------------|----------------|

当调用 existsByClientId("abc") 时返回 true,如何强制检查大小写?

实际结果:
existsByClientId("abc") --> true
existsByClientId("ABC") --> true

预期结果:
existsByClientId("abc") --> false
existsByClientId("ABC") --> true

Java version 8
Spring boot version 2.1.2.RELEASE
mysql-connector-java version 5.1.46

最佳答案

默认情况下,导出的 SQL 查询区分大小写。但是,如 document 中所述

The method parser supports setting an IgnoreCase flag for individual properties (for example, findByLastnameIgnoreCase(…)) or for all properties of a type that supports ignoring case (usually String instances — for example, findByLastnameAndFirstnameAllIgnoreCase(…)). Whether ignoring cases is supported may vary by store, so consult the relevant sections in the reference documentation for the store-specific query method.

由于我们使用的是 MySQL 数据库,区分大小写取决于服务器、数据库和连接排序规则,以及 default collation(utf8mb4_0900_ai_ci)不区分大小写,使比较不区分大小写。与其他数据库比较时产生意外结果。

来自 MySQL case insensitive select 的解决方案, 将列排序规则更改为区分大小写是最简单的,不需要更改代码。

关于java - Spring data JPA exists By Field在MySQL中不区分大小写,如何让它区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59350598/

相关文章:

java - 当 A 继承自 B 时从 EnumSet<A> 转换为 Set<B>

java - EclipseLink 在 OneToMany 关系中找不到实体

java - 这是备份带有流和异常的文件的正确方法吗?

java - 如何在我的 Java 项目中找到不需要的 JARS

Spring 正在失去与数据库的连接,并且无法恢复或重新连接

java - 当日历selenium java上出现2个日期时,如何选择可点击的日期?

MySQL:面对大量并发的正确性(SELECT ... FOR UPDATE)

javascript - 使用 jquery 隐藏多个选定的行

php - 检查两个给定开始时间和结束时间之间是否存在时间范围

java - 如何解决 Spring 问题