在 MyBatis 的 SQL映射文件中,有时候须要根据一些查询条件,来选择不一样的SQL语句,若是每个场景都重写SQL,很显然效率没有很高,而 MyBatis 的动态SQL很好的解决了这种问题,根据条件动态的处理 SQL, 特别简单的说就是,写一次SQL,可是根据分支等的跳转,在多个场景下也可使用,例如:java
<where>
标签包含<where>
可使用 <if test="....">
分条件进行处理,实现动态<foreach>
遍历标签放到后面代码中具体说在此以外,动态SQL同时结局了,在原生 JDBC 中须要拼接SQL语句时因为书写问题,而致使报错sql
/** * 根据条件查询 * @return */ List<User> findUserByCondition(User user);
<select id="findUserByCondition" resultType="cn.ideal.domain.User" parameterType="cn.ideal.domain.User"> select * from user <where> <if test="username != null"> and username = #{username} </if> <if test="gender != null"> and gender = #{gender} </if> </where> </select>
注意:在SQL中,“and” 用来拼接已有一个或多个查询条件的语句,当此语句为第一个查询条件的时候,会由于 <where>
的存在屏蔽第一个 “and”微信
/** * 根据条件查询 * @throws Exception */ @Test public void testFindByCondition() throws Exception{ User user = new User(); user.setUsername("汤姆"); user.setGender("女"); List<User> users = userMapper.findUserByCondition(user); for (User u : users){ System.out.println(u); }
有一些语句,在咱们的程序中,使用的频率特别高,这个时候,咱们也能够对其进行,单独的配置,而后达到复用的效果app
首先,咱们须要对其进行简单的声明dom
<sql id="xxxxx"> <!-- 复用的SQL --> </sql>
在须要引用的地方,咱们能够这样引用ide
<where> include refid="xxxxx"></include> <!-- 可能还用引用别的 --> </where>
提出这样一种需求,在用户中查询寻多个id,例如(12,16,17)咱们能够这样写SQLui
select * from user where id=12 or id=16 or id=17
或者这样idea
select * from user where id in (12,16,17)
而这种状况下,咱们须要向SQL中传递一个数据或者List类型的参数,而后使用 <foreach>
标签去遍历而后解析spa
/** * 根据QueryUserVo中提供的id集合,查询用户信息 * @param vo * @return */ List<User> findUserInIds(QueryUserVo vo);
<select id="findUserInIds" resultType="cn.ideal.domain.UserInstance" parameterType="cn.ideal.domain.QueryUserVo"> select * from user <where> <if test="ids != null and ids.size() > 0"> <foreach collection="ids" open="and id in (" close=")" item="uid" separator=","> #{uid} </foreach> </if> </where> </select>
解释一下code
本例中,我哦们使用了 select * from user where id in (12,16,17)
这种形式,若是想使用 or那种形式,只须要修改拼接格式就能够了
/** * 根据QueryUserVo中提供的id集合,查询用户信息 * @throws Exception */ @Test public void testfindUserInIds() throws Exception{ QueryUserVo vo = new QueryUserVo(); List<Integer> list = new ArrayList<Integer>(); list.add(12); list.add(16); list.add(17); vo.setIds(list); List<User> users = userMapper.findUserInIds(vo); for (User u : users){ System.out.println(u); } }
若是文章中有什么不足,欢迎你们留言交流,感谢朋友们的支持!
若是能帮到你的话,那就来关注我吧!若是您更喜欢微信文章的阅读方式,能够关注个人公众号
在这里的咱们素不相识,却都在为了本身的梦而努力 ❤一个坚持推送原创开发技术文章的公众号:理想二旬不止