<select id="selAll" resultType="com.caopeng.pojo.Flower">
select * from flower
</select> <select id="selCount" resultType="int">
select count(*) from flower
</select> <select id="selMap" resultType="com.caopeng.pojo.Flower">
select * from flower
</select>
package com.XXX.demo; import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map; import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.caopeng.pojo.Flower; public class Demo {
public static void main(String[] args) throws IOException {
//加载配置文件
InputStream in = Resources.getResourceAsStream("mybatis.xml");
//使用工厂设计模式 【注意】以后sqlSessionFactory都会被spring 管理,不需要我们自己创建
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(in); //获取sqlSession
SqlSession sqlSession=sqlSessionFactory.openSession(); //查询结果返回一个resultType的值作为泛型值的List
List<Flower> flowrList = sqlSession.selectList("com.caopeng.mapper.FlowerMapper.selAll");
for (Flower flower : flowrList) {
System.out.println(flower);
}
//查询结果返回一个Obejct
int count=sqlSession.selectOne("com.caopeng.mapper.FlowerMapper.selCount");
System.out.println(count); //查询结果返回一个Map,其中key值是selectMap的最后一个参数,value为resultType的指定的返回的对象
Map<Object,Object> map= sqlSession.selectMap("com.caopeng.mapper.FlowerMapper.selMap", "name");
System.out.println(map);
sqlSession.close();
}
}