mybaits九:自定义结果映射规则
生活随笔
收集整理的這篇文章主要介紹了
mybaits九:自定义结果映射规则
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
定義接口:?
package com.atChina.dao;import com.atChina.bean.Employee;public interface EmployeePlusMapper {public Employee getEmpByDepnos(Integer depno);}sql配置文件
<?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 namespace="com.atChina.dao.EmployeePlusMapper"><!-- resultMap標簽自定義某個javaBean的封裝規則,type屬性:自定義規則的Java類型id屬性: 唯一id,方便引用--><resultMap type="com.atChina.bean.Employee" id="defineEmp"><!-- id標簽 指定主鍵列的封裝規則id 定義主鍵,底層會優化column: 指定哪一列property:指定對應的javaBean屬性--><id column="deptno" property="deptno" /><!-- result標簽定義普通列封裝規則 --><result column="dname" property="dname" /><!-- 其他不指定的字段會自動封裝,但我們只要寫resultMap就盡量把全部的映射規則都寫上 --><result column="loc" property="loc" /></resultMap><!-- resultType="" resultMap=""只能有一個,不能同時設置這兩個屬性 --><select id="getEmpByDepnos" resultMap="defineEmp">select * from depttest a where deptno = #{deptno}</select> </mapper>?測試方法:
@Testpublic void test24() throws IOException {String resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);SqlSession openSession = sqlSessionFactory.openSession();try{// 命名空間.id,這樣別的配置文件里有同名的id,程序也不報錯EmployeePlusMapper em = openSession.getMapper(EmployeePlusMapper.class);System.out.println(em.getClass()); // 動態代理類Employee ee = em.getEmpByDepnos(10);System.out.println(ee);}finally{// 關閉openSession.close();}}?
總結
以上是生活随笔為你收集整理的mybaits九:自定义结果映射规则的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mybaits八:select查询返回m
- 下一篇: mybaits十:关联查询