Reason: when using the spring datajpa statement to query the null value of a field in the database table, such as:
findByIdAndNameIsNull
findByIdAndNameIsNotNull
When the value of name is empty string, the result of query is very different
1. Build tables
CREATE TABLE `user` ( `id` bigint(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) )
2. Compare the query of null between mysql and oracle Database
Mysql8.0.13:
UPDATE `user` u SET u.`name` = '' WHERE u.id = 4 SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NOT NULL--Valuable SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NULL--No value UPDATE `user` u SET u.`name` = NULL WHERE u.id = 4 SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NOT NULL--No value SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NULL--Valuable
Oracle11g:
UPDATE `user` u SET u.`name` = '' WHERE u.id = 4 SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NOT NULL--No value SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NULL--Valuable UPDATE `user` u SET u.`name` = NULL WHERE u.id = 4 SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NOT NULL--No value SELECT * FROM `user` u WHERE u.id = 4 AND u.`name` IS NULL--Valuable
To sum up, it can be seen that Oracle database thinks that no matter "empty string" or "null", Mysql is strictly null
3. Use the spring datajpa query statement to define null
JPA query
List<UserDo> findByIdAndNameIsNull; List<UserDo> findByIdAndNameIsNotNull;
Insert test data
INSERT INTO `user`(`id`, `name`, `age`) VALUES (4, NULL, 22); INSERT INTO `user`(`id`, `name`, `age`) VALUES (5, '', 22); INSERT INTO `user`(`id`, `name`, `age`) VALUES (6, '', 22);
Run and view results:
List<UserDo> findByIdAndNameIsNull;
id=4
List<UserDo> findByIdAndNameIsNotNull;
id=5 and id=6
Summary: JPA query thinks null is strictly null!
4. Air handling in actual operation
In actual production, we generally think that '' and null are empty, so when using JPA to query, we can use HQL to refine the query to avoid using the query with null
// Query empty fields SELECT u FROM UserDo u WHERE u.id = 4 AND (u.name is null or u.name ='') // Query non empty fields SELECT u FROM UserDo u WHERE u.id = 4 AND (u.name is not null or u.name <>'')