Mybatis是我们现在常用的一个框架,他的功能非常强大尤其是动态sql,我偶尔看到一篇帖子针对Mybatis动态sql的使用介绍的非常详细,所以给大家分享出来。
相关链接
[1]: https://mp.weixin.qq.com/s?__biz=MzIwMzY1OTU1NQ==&mid=2247493491&idx=1&sn=d83791e6bd0a093c83851010c00a75f7&chksm=96cea73fa1b92e29bd46dedcdadbdcf85d7c6d838d826aca7d72f99dbde37afe134ed8436cef&mpshare=1&scene=23&srcid=0801Lf2ZaJJlSCUi8MWjYIGc&sharer_sharetime=1597573639081&sharer_shareid=e503c766ca289af74ab1826a7f43b366%23rd
案例1,当入参是list时在xml中的parameterType可以不写,而resultType则写集合的泛型类型即可 代码片
.
// dao
User getUsersById(@Param("idls") List<String> idls);
// xml
<select id="getUsersById" resultType="com.beiyun.lcm.entity.User">
select auto_id as autoId,name as name ,age as age
from user
where id in
<foreach collection="idls" item="item" open="(" separator="," close=")">
#{
item}
</foreach>
</select>
案例2,当入参是map 代码片
.
// java
Map<String,String> map = new HashMap<> ();
map.put("userName","张三");
map.put("age","100");
this.userMapper.getUserByMap(map);
// dao
User getUserByMap(@Param("map") Map<String,Object> map);
// xml
<select id="getUsersById" resultType="com.beiyun.lcm.entity.User">
select auto_id as autoId,name as name ,age as age
from user
where name = #{
userName} and age =#{
age}
</select>
案例3,当入参是array 代码片
.
// dao
List<User> getUserls(@Param("ids") Integer[] ids);
// xml
<select id="getUserls" resultType="com.beiyun.lcm.entity.User">
select auto_id as autoId,name as name ,age as age
from user
where id in
<foreach index="index" collection="array" item="item" open="(" separator="," close=")">
#{
item}
</foreach>
</select>
案例3,当入参是字符串或者实体 代码片
.
// dao
List<User> getUserByName(@Param("name") String name);
// xml
<select id="getUserByName" resultType="com.beiyun.lcm.entity.User">
select auto_id as autoId,name as name ,age as age
from user
where name concat(“%”,name,“%”)
</select>
// dao
List<User> getUserList(User user);
// xml
<select id="getUserList" resultType="com.beiyun.lcm.entity.User">
select auto_id as autoId,name as name ,age as age
from user
// 直接用实体中的属性即可
where name concat(“%”,name,“%”),age =#{
age}
</select>
***当返回值值是一个集合时,resultType只要写泛型类型即可,mybatis会根据实际的查询结果进行映射处理。