同一JPA查询在不同开发者机器上返回结果不一致问题排查
本地环境JPA查询排除同ID逻辑失效问题
团队成员使用同一Git提交版本、相同数据库内容、一致的构建调试流程,唯独我的机器上出现异常:JPA查询的同ID实体排除逻辑失效。
该查询用于检查指定实体是否重复,会显式排除ID相同的条目(避免实体与自身对比),但在我的机器上,查询仍会找到同ID实体并抛出NotUniqueException。移除其中一个OR条件后,排除逻辑恢复正常,我怀疑是查询的括号优先级问题,但调试时生成的SQL看起来是正确的。
简化代码
import com.mysema.query.BooleanBuilder; import com.mysema.query.jpa.impl.JPAQuery; public class ExampleClass { @Autowired protected ClassThatExtendsJpaRepository customerDAO; public void checkUniqueness(Customer inputCustomer) throws NotUniqueException { // OR条件 BooleanBuilder condition = new BooleanBuilder(); condition.or(QCustomer.customer.registerNr.eq(inputCustomer.getRegisterNr())); condition.or(QCustomer.customer.registerNr.eq(inputCustomer.getRegisterNr())); JPAQuery query = new JPAQuery().from(QCustomer.customer).where(condition); // 本应排除同ID客户,但无效果 query.where(QCustomer.customer.id.ne(inputCustomer.getId())); Customer existingCustomer = customerDAO.findOne(query); // 结果:找到同ID客户!本应无结果! if(existingCustomer != null) { throw new NotUniqueException(); } } }
(注:原代码存在拼写错误,已修正Qcustomer为QCustomer、Condition.or为condition.or)
生成的SQL(调试显示)
Select customer from Customer customer where (customer.registerNr = ?1 or customer.registerNr = ?1) and customer.id <> ?2
直接在数据库执行该SQL结果正确,但我怀疑实际运行时生成的SQL括号位置错误:
Select customer from Customer customer where customer.registerNr = ?1 or (customer.registerNr = ?1 and customer.id <> ?2)
使用版本
- Spring-data-jpa: 1.9.6.RELEASE
- com.mysema.querydsl: 3.7.4
- Hibernate: 4.2.21.Final
- OJDBC: 19.17.0.0
- Database: Oracle Database 21c Express Edition Release 21.0.0.0.0 - Production
- Java: 8
我们不想修改代码,希望找到本地环境层面的原因并解决。
内容的提问来源于stack exchange,提问作者MJL
相关产品推荐
相关产品推荐

