SqlSession对象本身的API中就有三个查询方法,分别能够实现如下查询方式
1返回单个对象 selectOne
2返回对象List集合 selectList
3返回对象Map集合 selectMap
接下来我们就对这三个方法进行一个快速的学习
创建Emp实体类
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Emp implements Serializable {
private Integer empno;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private Double sal;
private Double comm;
private Integer deptno;
}
准备Mapper映射文件
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
sqlMapConfig中导入EmpMapper映射文件
测试代码
package com.msb.test;
import com.msb.pojo.Dept;
import com.msb.pojo.Emp;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @Author: Ma HaiYang
* @Description: MircoMessage:Mark_7001
*/
public class Test2 {
private SqlSession sqlSession;
@Before
public void init(){
SqlSessionFactoryBuilder ssfb =new SqlSessionFactoryBuilder();
InputStream resourceAsStream = null;
try {
resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory factory=ssfb.build(resourceAsStream) ;
sqlSession=factory.openSession();
}
@Test
public void testSelectOne(){
// 查询单个对象
System.out.println("sqlSession查询单个对象");
Emp emp = sqlSession.selectOne("findOne");
System.out.println(emp);
}
@Test
public void testSelectList(){
// 查询多个对象的List集合
System.out.println("sqlSession查询对象List集合");
Listemps = sqlSession.selectList("EmpMapper.findAll");
emps.forEach(System.out::println);
}
@Test
public void testSelectMap(){
// 查询多个对象的Map集合
System.out.println("sqlSession查询对象Map集合");
MapempMap = sqlSession.selectMap("findEmpMap", "EMPNO");
Setempnos = empMap.keySet();
for (Integer empno : empnos) {
System.out.println(empno+" :" +empMap.get(empno));
}
}
@After
public void release(){
// 关闭SQLSession
sqlSession.close();
}
}
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net