MyBatis的parameterType传入参数类型
1、mybatis传入的参数可以是基本数据类型int、string、long、Date;或者是类(JavaBean、Integer等)和Map
2、如何获取参数中的值:
2.1 基本数据类型:#{参数} 获取参数中的值
2.2 复杂数据类型:#{属性名} ,map中则是#{key}
3、常用类型参数的案例
3.1传入List
<select id="findUserListByIdList" parameterType="java.util.ArrayList" resultType="User">
select * from user user
<where>
user.ID in (
<foreach collection="list" item="id" index="index" separator=",">
#{id}
</foreach>
)
</where>
</select>
在使用foreach的时候最关键的也是最容易出错的就是collection属性。
该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:
1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可
3.2传入数组
<select id="findUserListByIdList" parameterType="java.util.HashList" resultType="User">
select * from user user
<where>
user.ID in (
<foreach collection="array" item="id" index="index" separator=",">
#{id}
</foreach>
)
</where>
</select>
3.3传入map
该案例中:
map {
“idList”:“{...}”,
“id”:“”,
“code”:“”,
}
<select id="exists" parameterType="java.util.HashMap" resultType="java.lang.Integer">
SELECT COUNT(*) FROM USER user
<where>
<if test="code != null">
and user.CODE = #{code}
</if>
<if test="id != null">
and user.ID = #{id}
</if>
<if test="idList !=null ">
and user.ID in (
<foreach collection="idList" item="id" index="index" separator=",">
#{id}
</foreach>
)
</if>
</where>
</select>
collection中放键名
3.4传入java对象
和传入map类似,例如java对象为
public class User{
private int id;
private String code;
private List<Integer> idList;
}
<select id="findUserList" parameterType="User" resultType="java.lang.Integer">
SELECT COUNT(*) FROM USER user
<where>
<if test="code != null">
and user.CODE = #{code}
</if>
<if test="id != null">
and user.ID = #{id}
</if>
<if test="idList !=null ">
and user.ID in (
<foreach collection="idList" item="id" index="index" separator=",">
#{id}
</foreach>
)
</if>
</where>
</select>
collection里面放变量名
转载:
作者:Remember_Ray
来源:CSDN
原文:https://blog.csdn.net/q343509740/article/details/80578832
转载于//www.cnblogs.com/DiiDii/p/10990127.html
还没有评论,来说两句吧...