MyBatis入门【六】动态SQL
2018-01-30 01:11
330 查看
在MyBatis中,运用动态SQL可以进行动态的添加操作数据库的条件,使操作数据库更加灵活
id:SQL片段唯一标识
经验:
1、基于单表来定义SQL片段,SQL片段可重用性高
2、在SQL片段中不要包含where
引用SQL片段
1、select * from user where id=1 or id=10 or id=123
包装类的定义
mapper.xml文件中SQL片段:
效果串: AND (id=1 or id=10 or id=123)
2、select * from user where id in (1,10,123)
效果串: AND id IN(1 ,10, 23)
代码示例
<!-- where可以自动去掉条件中的第一个and --> <select id="findUserList" parameterType="UserQueryVo全路径/别名" resultMap="UserCustom全路径"> SELECT * FROM USER <where> <if test="userCustom != null"> <if test="userCustom.sex != null and userCustom.sex != ' ' "> and user.sex = #{userCustom.sex} </if> <if test="userCustom.username != null and userCustom.username != ' ' "> and user.username LIKE '%${userCustom.username}%' </if> </if> </where> </select>
SQL片段
将动态SQL代码抽取出来形成SQL片段,其他statement就可以调用定义SQL片段,id:SQL片段唯一标识
经验:
1、基于单表来定义SQL片段,SQL片段可重用性高
2、在SQL片段中不要包含where
<sql id="query_user_where"> <if test="userCustom != null"> <if test="userCustom.sex != null and userCustom.sex != ' ' "> and user.sex = #{userCustom.sex} </if> <if test="userCustom.username != null and userCustom.username != ' ' "> and user.username LIKE '%${userCustom.username}%' </if> </if> </sql>
引用SQL片段
<select id="findUserList" parameterType="UserQueryVo全路径/别名" resultMap="UserCustom全路径"> SELECT * FROM USER <where> <!-- 引用SQL片段 id,如果不在本mapper文件中,需要前边添加namespace --> <include refid="query_user_where"></include> <!-- 在这里还可引用其他SQL片段 --> </where> </select>
foreach
向SQL中传递数组或List,mybatis使用foreach解析1、select * from user where id=1 or id=10 or id=123
包装类的定义
public class UserQueryVo{ //传入多个id private List<Integer> ids; //在此处应生成setget }
mapper.xml文件中SQL片段:
<!-- 使用foreach遍历ids collection:指定输入对象中集合属性 item:每个遍历生成对象串 open:开始遍历时拼接的串 close:结束遍历时拼接的串 separator:遍历的两个对象中需要拼接的串 --> <foreach collection="ids" item="user_id" open="AND (" close=")" separator="or"> <!-- 每个遍历需要拼接的串--> id=#{user_id} </foreach>
效果串: AND (id=1 or id=10 or id=123)
2、select * from user where id in (1,10,123)
<foreach collection="ids" item="user_id" open="AND id IN (" close=")" separator=","> <!--每个遍历需要拼接的串--> i#{user_id} </foreach>
效果串: AND id IN(1 ,10, 23)
相关文章推荐
- Mybatis入门(四) -- 动态SQL
- mybatis入门基础(五)----动态SQL
- mybatis入门基础----动态SQL
- 史上最简单的MyBatis动态SQL入门示例代码
- MyBatis入门——动态SQL
- mybatis入门基础(五)----动态SQL
- mybatis入门-动态sql
- mybatis入门基础(五)----动态SQL
- MyBatis3入门程序(04_动态SQL)
- MyBatis入门06 动态sql语句
- MyBatis入门——动态SQL
- MyBatis入门(四)---动态SQL
- mybatis入门基础(五)----动态SQL
- JAVAWEB开发之mybatis详解(一)——mybatis的入门(实现增删改查操作)、自定义别名、抽取代码块以及动态SQL的使用
- SpringBoot入门-19(springboot集成mybatis注解形式增删查改properties配置,利用《script》实现动态SQL)
- MyBatis入门07--实现sql动态模糊查询
- mybatis入门基础(五)----动态SQL
- Mybatis入门教程(四)之mybatis动态sql
- mybatis入门基础(五)----动态SQL
- mybatis之入门到开发(三)之常用对象SqlSessionFactory和SqlSession,动态sql,输入映射和输出映射