第一节中查询的方法返回类型为Student,当返回类型为List<Student>时怎么办呢?
这时需要配置resultMap标签.
<?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">
<!-- namespace:Mapper映射 -->
<!-- 这个文件感觉就像StudentMapper接口的实现一样,只是从java文件变成了xml文件
充当了Dao类的功能
-->
<mapper namespace="com.skymr.mybatis.mappers.StudentMapper">
<select id="getStudent" parameterType="int" resultType="Student">
<!-- mybatis要自己写sql语句 -->
select * from mybatis_Student where id=#{id}
</select>
<!-- 查询所有学生 -->
<!-- resultMap属性要对应 resultMap的id属性 -->
<select id="getAllStudents" resultMap="studentMap">
select * from mybatis_Student
</select>
<resultMap type="Student" id="studentMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
</mapper>
package com.skymr.mybatis.mappers;
import java.util.List;
import com.skymr.mybatis.model.Student;
public interface StudentMapper {
public Student getStudent(int id);
public List<Student> getAllStudents();
}
package com.skymr.mybatis.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.skymr.mybatis.mappers.StudentMapper;
import com.skymr.mybatis.model.Student;
import com.skymr.mybatis.util.MybatisUtil;
public class StudentTest2 {
private Logger logger = LoggerFactory.getLogger(StudentTest2.class);
private SqlSession session;
@Before
public void beforeTest(){
session = MybatisUtil.openSession();
}
@After
public void afterTest(){
session.close();
}
@Test
public void testGetAllStudents(){
logger.info("测试取得所有学生");
StudentMapper mapper = session.getMapper(StudentMapper.class);
List<Student> list = mapper.getAllStudents();
logger.info(list.toString());
}
}