1.单表查询时,ResultMap的使用方法
studentMapper.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.bb.mapper.StudentMapper">
<!--使用resultMap-->
<select id="selectWithResultMap" resultMap="studentResultMap">
select * from student
</select>
<!-- id对应select标签的resultMap值,type为sql语句的返回值类型-->
<resultMap id="studentResultMap" type="Student">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="age" column="age"></result>
</resultMap>
</mapper>
StudentMapper.java
package com.bb.mapper;
import com.bb.entity.Student;
import org.apache.ibatis.annotations.Select;
import java.util.HashMap;
public interface StudentMapper {
/*
* 1。方法名和StudentMapper.xml文件中标签的id值一致
* 2。方法输入参数与StudentMapper.xml文件中标签的parameterType一致
* 3。返回值与StudentMapper.xml文件中标签的resultType一致
*
*/
Student selectStudent(int id);
Student selectStudentByParams(Student student);
Student selectStudentByParams2(HashMap map);
//返回值为resultMap中的type的值
Student selectWithResultMap();
}
TestMybatis.java
package com.bb.service;
import com.bb.entity.Student;
import com.bb.mapper.StudentMapper;
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 java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
public class TestMybatis {
//使用ResultMap接收sql返回值
public static void queryWithResultMap() throws IOException {
Reader resourceAsReader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsReader);
SqlSession sqlSession = sqlSessionFactory.openSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
Student student = mapper.selectWithResultMap();
System.out.println("使用ResultMap接收sql返回值:");
System.out.println(student.getId()+"-"+student.getName()+"-"+student.getAge());
}
public static void main(String[] args) throws IOException {
queryWithResultMap();
}
}
2.多表联合查询时,ResultMap的使用方法
见第十章 一对一联合查询的第二种方法
2.使用ResultMap实现