初识Mybatis(六)之动态sql
2018-01-16 11:52
447 查看
Mybatis的标签
在写sql语句中,有两个连接条件如果一个没有值,则查询结果会为空select * from user where username = ” 唐宝宝” and adderss = “林大”
如果在username传入的参数为null,或者每一传递,则查询结果为空
可以用if来判断,得出结果
<if test="username != null and username!=''"> username = #{username } </if> <if test="adderss != null and adderss !=''"> and adderss= #{adderss} </if>
where
<!-- where标签可以自动添加where,同时处理sql语句中第一个and关键字 -->
<where>
<if test="username != null and username!=''"> username = #{username } </if> <if test="adderss != null and adderss !=''"> and adderss= #{adderss} </if>
</where>
sql片段:
在书写sql语句时候,会有一些重复的sql片段,比如,select * from user
Mybatis中可以使将这些相同的片段组合起来,罅隙调用直接用相依的标签就可以
<!-- sql片段 --> <sql id="selector"> select * from user </sql> <!--调用sql片段--> <select id="findUserByIdsArray" resultType="User" parameterType="QueryVO"> <include refid="selector"></include> </select>
foreach标签:
在查询的时候,有时候要查询某几个特定的值,普通sql要这样写:
select * from user wh
4000
ere user_id in(1,2,3,4);
但是要用之前的办法无法达到动态修改,要想在程序中动态修改,Mybatis为我们带来了Foreach标签
<!-- foreach查询多个ID --> <!-- 包装集合 --> <select id="findUserByIds" resultType="User" parameterType="QueryVo"> <include refid="selector"></include> <where> id in <foreach collection="idlist" item="id" separator="," open="(" close=")"> #{id} </foreach> </where> </select> <!-- 包装数组 --> <select id="findUserByIdsArray" resultType="User" parameterType="QueryVO"> <include refid="selector"></include> <where> id in <foreach collection="ids" item="id" separator="," open="(" close=")"> #{id} </foreach> </where> </select> <!-- 普通集合 --> <select id="selectUserByids" resultType="user" parameterType="QueryVo"> <include refid="selector"> </include> <where> id in <foreach collection="list" item="id" separator="," open="(" close=")"> #{id} </foreach> </where> </select> <!--普通数组 --> <select id="selectUserByIdsArray" resultType="User"> select * from user where id in <foreach collection="array" item="id" separator="," open="(" close=")"> #{id} </foreach> </select> <!-- ofType:泛型的类型 --> <resultMap type="User" id="userOrders"> <id column="uid" property="id"/> <result column="username" property="username"/> <collection property="orders" ofType="Orders"> <id column="oid" property="id"/> <result column="number" property="number"/> <result column="user_id" property="userId"/> </collection> </resultMap>
相关文章推荐
- MyBatis动态sql_choose分支选择
- mybatis的动态sql
- mybatis 动态sql之Map参数
- mybatis中的动态SQL
- MyBatis-动态SQL
- MyBatis的动态sql详解
- MyBatis的动态SQL详解
- MyBatis动态SQL
- mybatis详解-(17)动态SQL
- Spring3 整合MyBatis3 配置多数据源 动态选择SqlSessionFactory
- mybatis动态sql根据java枚举判断不执行,执行otherwise,解决办法
- MyBatis学习 之 动态SQL语句
- MyBatis 动态拼接Sql字符串的问题
- mybatis动态SQL语句
- Mybatis的动态sql详解,区别于传统的sql拼写
- mybatis中修改数据库单一数据时,连带清空其他数据的问题【动态sql】
- SSM框架day02-MyBatis——034——符合查询问题演示、035——动态SQL
- Mybatis 动态Sql
- Mybatis之动态 SQL
- mybatis 学习记录(3)—— 动态 sql