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/