一、sqlsession的三种查询方式
test代码
//1.读取资源
InputStream resource = Resources.getResourceAsStream("mybatis.xml");
//2.创建sessionFactory
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resource);
//3.创建session
SqlSession session = build.openSession();
//4.调用方法
List<Flower> list = session.selectList("com.xie.mapper.FlowerMapper.selectAll");
System.out.println(list);
Flower one = session.selectOne("com.xie.mapper.FlowerMapper.selectOne", 2);
Flower one1 = session.selectOne("com.xie.mapper.FlowerMapper.selectOne2", list.get(0));
System.out.println(one1);
System.out.println(one.getName());
session.close();
xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xie.mapper.Flower">
<select id="selectAll" resultType="flower">
select * from flower
</select>
<select id="selectOne" resultType="flower" parameterType="int">
select * from flower where id = #{id}
</select>
<select id="selectOne2" resultType="flower" >
select * from flower where id = #{id} and name = #{name}
</select>
</mapper>
- selectOne(String namespace,Object param)
- selectList(String namespace,Object param)
- selectMap(String namespace,Object param)
可以看到,这三种方式只允许我们传入一个参数,若需要传入多个参数怎么办呢?
二、sqlsession的传参方式
传参可以不用在sql语句标签中加paramType属性,会自动识别。
- 传入单个参数
- 传入整个对象
- 传入一个map
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xie.mapper.Flower">
<select id="selectAll" resultType="flower">
select * from flower
</select>
传入单个参数
<select id="selectOne" resultType="flower" parameterType="int">
select * from flower where id = #{id}
</select>
传入一个flower对象,id,name都是它的属性
<select id="selectOne2" resultType="flower" >
select * from flower where id = #{id} and name = #{name}
</select>
传入的参数是一个map,key1对应id,key2对应name
<select id="selectOne3" resultType="flower>
select * from flower where id=#{key1} and name=#{key2}
</mapper>
三、Mapper代理
- xml文件的namespace必须是接口的全路径,通过这个namespace将xml作为接口的实现类
- 一个接口职能对应一个xml,不能多个
- 接口最好与xml同名
package com.xie.mapper;
import com.xie.entity.Flower;
import java.util.List;
//多参的传递其实相当于传入一个map,{(param1,参数1),(param2,参数2).....}
public interface FlowerMapper {
List<Flower> selectMore(String name,String production);
List<Flower> selectMore2(String id,String production);
int update(Flower f);
}