老司机学习MyBatis之如何使用动态SQL之使用where条件

本文探讨了在MyBatis中遇到的动态SQL问题,特别是当使用where条件时,如何处理id为空的情况。通过两种解决方案——添加1=1条件和使用where标签——来避免SQL语句拼接错误。实验结果显示,where标签能有效移除多余的and或or,但需注意and的位置,避免引发错误。
摘要由CSDN通过智能技术生成

一、前言

前面一节我们最后留下了一个疑问,如果第一个条件当id为空的时候,我们的SQL语句拼接就产生了问题,我们先通过案例复现一下这个问题,修改testFindEmpByCondition方法

@Test
public void testFindEmpByCondition() throws IOException {
	SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
	SqlSession openSession = sqlSessionFactory.openSession();
	try {
		EmpMapper mapper = openSession.getMapper(EmpMapper.class);
		Emp emp = new Emp(null,"ant","ant@sina.com",1);
		Emp empFind = mapper.findEmpByConditions(emp);
		System.out.println(empFind);
	} finally {
		openSession.close();
	}
}

控制台打印如下

org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值