上个的例子是数据库表的字段和Java实体类属性一一对应,现在处理不对应的情况需要使用resultMap作映射

SQL语句

drop table if exists person;

create table person(  
    person_id int(10) not null auto_increment,
    name varchar(10),
    gender int(1),
    person_addr varchar(50),
    birthday date,
    primary key(person_id)
);

insert into person values(1, '阿满', 1, '魏国', '2014-10-11');  

Person实体类

public class Person {

    private Integer personId;
    private String name;
    private Integer gender;
    private String personAddr;
    private Date birthday;
    // ... get set
}

PersonMapper.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.itbto.mapper.PersonMapper">

    <!-- 
        resultMap:组装从数据库表中查询出来的自定义实体
        type:实体的数据类型
        id:resultType的唯一标识
     -->
    <resultMap type="com.itbto.mode1.Person" id="personResultMap">
        <!-- 
            id列只有一个
            column:表的字段名
            property:实体的属性名
         -->
        <id column="person_id" property="personId"/>
        <result column="name" property="name"/>
        <result column="gender" property="gender"/>
        <result column="person_addr" property="personAddr"/>
        <result column="birthday" property="birthday"/>
    </resultMap>

    <select id="selectPersonById" parameterType="java.lang.Integer" resultMap="personResultMap">
        select * from person where person_id = #{id}
    </select>

    <!-- 
        resultType:返回不需要映射的字段
     -->
    <select id="selectPersonCount" resultType="java.lang.Integer">
        select count(*) from person
    </select>
</mapper>  

在SqlMapConfig.xml中添加

<mapper resource="com/itbto/mapper/PersonMapper.xml"/>  

测试

@Test
public void testSelectPersonById(){  
    SqlSession session = sessionFactory.openSession();
    try {
        //selectOne:第一个参数:要执行的sql,命名空间.sql的id
        //第二个参数是传递给sql的实际参数
        com.itbto.mode1.Person person = session.selectOne("com.itbto.mapper.PersonMapper.selectPersonById", 1);
        System.out.println(person);
    } catch (Exception e) {
        e.printStackTrace();
    } finally{
        session.close();
    }
}

@Test
public void testSelectPersonCount(){  
    SqlSession session = sessionFactory.openSession();
    try {
        Integer count = session.selectOne("com.itbto.mapper.PersonMapper.selectPersonCount");
        System.out.println(count);
    } catch (Exception e) {
        e.printStackTrace();
    } finally{
        session.close();
    }
}