1. 程式人生 > >Mybatis3.0-[tp_28-29]-對映檔案-resultMap_自定義結果集對映規則_及關聯環境的搭建

Mybatis3.0-[tp_28-29]-對映檔案-resultMap_自定義結果集對映規則_及關聯環境的搭建

筆記要點
出錯分析與總結
工程組織

 

1.定義介面  EmployeeMapperPlus.java

package com.dao;
import com.bean.*;
public interface EmployeeMapperPlus {
    public Employee getEmpById(Integer id);
}

 

2.定義對映檔案    EmployeeMapperPlus.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.dao.EmployeeMapperPlus"> <!--ResultMap ;自定義結果集對映規則; type: 自定義規則的Java型別;id: 唯一的標識,方便引用--> <resultMap id="MyEmp" type="com.bean.Employee"
> <!--指定主鍵列的封裝規則,id定義主鍵,底層會有優化規則; column : 指定具體的那一列; property:指定的JavaBean對應的屬性--> <id column="id" property="id"/> <!--定義普通列的封裝規則--> <result column="last_name" property="lastName"/> <!--,其他不指定的列會自動封裝;我們只要寫ResultMap,就把剩下的對映全部都寫上
--> <result column="email" property="email"/> <result column="gender" property="gender"/> </resultMap> <!--public Employee getEmpById(Integer id); 注意進行更改為resultMap--> <select id="getEmpById" resultMap="MyEmp"> select * from tbl_employee where id=#{id} </select> <!--場景1 --> </mapper>

 

(關閉了駝峰規則,驗證自定義配置)

 


3.編寫測試程式碼  test_tp28

public class test_tp28 {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream=Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }
    @Test
    public void test06() throws Exception{
        //預設是不自動提交資料的,需要我們自己手動提交
        SqlSession openSession = getSqlSessionFactory().openSession();
        try {
            EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
            Employee empById = mapper.getEmpById(1);
            System.out.println(empById);

            //最後手動提交
            openSession.commit();
        }finally {
            openSession.close();
        }
    }

}

 

測試結果

DEBUG 11-29 17:32:44,565 ==>  Preparing: select * from tbl_employee where id=?   (BaseJdbcLogger.java:145) 
DEBUG 11-29 17:32:44,584 ==> Parameters: 1(Integer)  (BaseJdbcLogger.java:145) 
DEBUG 11-29 17:32:44,597 <==      Total: 1  (BaseJdbcLogger.java:145) 
Employee{id=1, lastName='jerry', email='[email protected]', gender='1'}