MyBatis动态Sql
来源:互联网 发布:cctv2郑州淘宝诈骗 编辑:程序博客网 时间:2024/06/14 17:34
动态 SQL是MyBatis强大特性之一。可以实现sql语句的拼装。
sql映射文件:
<select id="getEmpsByCondition" resultType="com.test.beans.Employee"> SELECT * FROM tb1_emplyee where <if test="id!=null"> id=#{id} </if> <if test="lastName!=null"> AND last_name LIKE #{lastName} </if> <if test="email!=null"> AND email=#{email} </if> /*ognl会进行字符串以及数字的转换判断*/ <if test="gender==0 or gender==1"> AND gender=#{gender} </if></select>
对应的接口文件:
public interface EmployeeMapperDymanicSQL { //些带了那个字段查询条件就带上这个字段的值 public List<Employee> getEmpsByCondition(Employee employee);}
测试方法:
@Testpublic void testDynamicSqlTest() throws IOException{SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();//1、获取到的SqlSession不会自动提交数据SqlSession openSession = sqlSessionFactory.openSession();try{ EmployeeMapperDymanicSQL mapper=openSession.getMapper(EmployeeMapperDymanicSQL.class); Employee employee=new Employee(1,"%e%",null,"3"); List<Employee> emps=mapper.getEmpsByCondition(employee); for (Employee e:emps){System.out.println(e); }} finally {openSession.close();}}全局配置文件:
<mappers><mapper resource="EmployeeMapperDymanicSQL.xml"/></mappers>
sql语句会根据if标签中的内容动态进行拼装,但是如果第一个id值设置为null必然会导致错误,下面有两种解决方案:
1.where 1=1 后面全部跟and
ex:
<select id="getEmpsByCondition" resultType="com.test.beans.Employee"> SELECT * FROM tb1_emplyee where 1=1 <if test="id!=null"> AND id=#{id} </if> <if test="lastName!=null"> AND last_name LIKE #{lastName} </if> <if test="email!=null"> AND email=#{email} </if> /*ognl会进行字符串以及数字的转换判断*/ <if test="gender==0 or gender==1"> AND gender=#{gender} </if></select>或者使用where标签:
<mapper namespace="com.test.dao.EmployeeMapperDymanicSQL"> <!--public List<Employee> getEmpsByCondition(Employee employee);--> <select id="getEmpsByCondition" resultType="com.test.beans.Employee"> SELECT * FROM tb1_emplyee <where> <if test="id!=null"> id=#{id} </if> <if test="lastName!=null"> AND last_name LIKE #{lastName} </if> <if test="email!=null"> AND email=#{email} </if> /*ognl会进行字符串以及数字的转换判断*/ <if test="gender==0 or gender==1"> AND gender=#{gender} </if> </where> </select></mapper>
阅读全文
0 0
- mybatis动态SQL语句
- MyBatis动态SQL
- MyBatis 动态SQL
- Mybatis 动态SQL
- MyBatis动态SQL
- MyBatis动态SQL完整版
- mybatis动态sql
- mybatis动态SQL语句
- mybatis动态SQL语句
- MyBatis的动态SQL
- MyBatis动态SQL
- MyBatis动态SQL
- MyBatis 动态SQL语句
- MyBatis动态SQL
- Mybatis组建动态SQL
- MyBatis 动态sql
- mybatis 动态SQL语句
- MyBatis动态SQL详解
- Linux Deepin
- Kotlin简单使用
- 第3节---爬取知乎‘美女’
- JS初级基础
- Springboot使用FastJson后,接口返回中文乱码的问题解决。
- MyBatis动态Sql
- oracle function函数
- web前端到底怎么学?干货资料!
- Electron 打包时下载 xxx-electron-v1.6.8-<arch>-x64.zip 文件出错
- awk使用
- 三分天下如何选择vue,angular,react
- 设计模式练习--工厂模式
- POJ
- 70. Climbing Stairs