Mybatis参数传递
一、mybatis 传递单个参数
1.单参数赋值
例如:
dao:public void deletePerson(Integer id);
mapper(xml):
<delete id="" parameterType=""> delete from person where id =#{id}</delete>
<delete id="" parameterType=""> delete from person where id =#{param}</delete>
//#{参数名}多参数不能用这样的形式
//只能用#{param1}
二、传递多个参数
1.使用javabean传递参数
2.使用map(k/v)传递参数
3.使用注解@param传递参数
4.默认方法
例如:(方法4)
dao:public person getPersonByNameAndGander(String name, String gander);
mapper(xml):
<select id="" parameterType="">
select * from person where username=#{param1} and gander=#{param2}
</select>
例如:(方法1)
封装成POJO类 当参数较多建议使用
dao:public person getPersonByNameAndGander(Person person);
mapper(xml):
select * from person where username=#{username} and gander=#{gander}
//注意使用时,person类要有通过username和gander两个参数的构造方法
例如:(方法2)
封装成map(值较少,没有对应的对象)
dao:public person getPersonByNameAndGander(Map<String,Object> param);
mapper(xml):
select * from person where username=#{username} and gander=#{gander}
//使用时,要先new一个map然后put值,key与#{}一致
put(“username”,“A”)
put(“gander”,“B”)
例如:(方法3)这个最简单
使用@param,mybatis自动封装成map
dao:
public person getPersonByNameAndGander(@param("username")String username,@param("gander") String gander);
<select id="" parameterType="">
select * from person where username=#{username} and gander=#{gander}
</select>
三、方法的使用
public class MyBatisTest {
public static SqlSessionFactory sqlSessionFactory = null;
public static SqlSessionFactory getSqlSessionFactory() { //相当于创建一个数据库对象
if (sqlSessionFactory == null) {
String resource = "mybatis-config.xml";//配置文件的位置
try {
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
return sqlSessionFactory;
}
public void deletePerson(){
SqlSession sqlSession = this.getSqlSessionFactory().openSession();//链接数据库
PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);//XML文件
personMapper.deletePerson(5);//调用方法
sqlSession.commit();//提交事务,查询不需要
}
}
四、处理集合类型的参数
1.当参数类型为collection,默认转换成map map的key为collection
2.当参数类型为list,处理collection的值意外,list作为key
3.当参数类型为数组,key是array
例如:
dao:public person getPersonByName(Collection c1);//数组改成
mapper(xml):
<select id="" parameterType="">
select * from person where username=#{collection[i]} //小写 数组改成Array[]
</select>
或者用@param起别名
dao:public person getPersonByName(@param("a") Collection c1);
mapper(xml):
<select id="" parameterType="">
select * from person where username=#{a[i]}
</select>
五、foreach标签,传一系列参数
例如:
dao:public list getPersonByIDs (@param(“ids”)Collection c1);//数组改成
mapper(xml):
<select id="getPersonByIDs" parameterType="person">
select * from person where id in
<foreach collection="array"
item="id" index="i" //item是每一个 index 是序号
open="(" close=")" //open 是开始的字符,close是结束的字符 一般是写死的
separator=",">//separator是用什么分隔
#{id}//是循环的什么
</foreach>
</select>