1. 程式人生 > >MyBatis_Study_003(字段名與屬性名稱不一致,resultMap)

MyBatis_Study_003(字段名與屬性名稱不一致,resultMap)

nts p標簽 ins imp drive for ase type屬性 column

源碼:https://github.com/carryLess/mbtsstd-003

1.主配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- (以上)文件頭在解壓的文件夾中mybatis-3.4.4.pdf文件中搜索mybatis-3-config.dtd即可得到 -->
<configuration
> <!-- 指定屬性配置文件 --> <properties resource="jdbc.properties" /> <!-- 配置類的別名,我建議使用package這種寫法 這樣寫會將該包中所有類的簡單類名配置為別名,簡單方便 ,還有別的寫法,自行google --> <typeAliases> <package name="model" /> </typeAliases> <!-- 配置MyBatis運行環境
--> <environments default="development"> <environment id="development"> <!-- 使用JDBC事務管理 --> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <!-- 註冊映射文件 --> <mappers> <mapper resource="dao/mapper.xml"/> <!-- 實際開發中可能有多個映射文件,而其中sql標簽的id相同時候,執行過程就會報錯 我們可以根據mapper映射文件中的namespace屬性來區分,調用時候用如下方式 namespace.id --> <!-- <mapper resource="dao/mapper2.xml"/> --> </mappers> </configuration>

2.mapper映射文件

<?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">
<!-- 文件頭在解壓的文件夾中mybatis-3.4.4.pdf文件中搜索mybatis-3-mapper.dtd即可得到 -->
<mapper namespace="model.SStudent">
    <!-- parameterType屬性,框架會根據SQLSession中傳遞的參數檢測到,所以我們一般不用指定 -->
    <insert id="insertStudentByList">
        insert into SStudent(sname,sage,score) values
        <!-- 這裏面的collection必須寫成list -->
        <foreach collection="list" separator="," item="stu">
            (#{stu.name},#{stu.age},#{stu.score})
        </foreach>
    </insert>

    <!-- 使用別名 -->
    <select id="selectById1" resultType="SStudent">
        select sid id,sname name,sage age,score from sstudent where sid = #{xxx}
    </select>

    <!-- 使用resultMap -->
    <select id="selectById2" resultMap="sStudentMapper">
        select sid,sname,sage,score from sstudent where sid = #{xxx}
    </select>

    <!--
        type:要映射的實體類
        id:resultMap標簽的id,用於select標簽中resultMap屬性
    -->
    <resultMap id="sStudentMapper" type="SStudent">
        <id column="sid" property="id" />
        <result column="sname" property="name" />
        <result column="sage" property="age" />
    </resultMap>

</mapper>

3.實體類

package model;

/**
 * Created by carryLess on 2017/11/29.
 */
public class SStudent {
    private Integer id;
    private String name;
    private Integer age;
    private double score;

    public SStudent() {
    }

    public SStudent(String sname, Integer sage, double score) {
        this.name = sname;
        this.age = sage;
        this.score = score;
    }

    @Override
    public String toString() {
        return "SStudent{" +
                "id=" + id +
                ", sname=‘" + name + ‘\‘‘ +
                ", sage=" + age +
                ", score=" + score +
                ‘}‘;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSname() {
        return name;
    }

    public void setSname(String sname) {
        this.name = sname;
    }

    public Integer getSage() {
        return age;
    }

    public void setSage(Integer sage) {
        this.age = sage;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}

4.dao接口與實現類

package dao;

import model.SStudent;

import java.util.List;
import java.util.Map;

/**
 * Created by carryLess on 2017/11/29.
 */
public interface IStudentDao {

    /**
     * 插入集合
     * @param studentList
     */
    void insertStudentByList(List<SStudent> studentList);

    /**
     * 根據id查詢1
     * @param id
     * @return
     */
    SStudent selectById1(int id);

    /**
     * 根據id查詢2
     * @param id
     * @return
     */
    SStudent selectById2(int id);
}
package dao;

import model.SStudent;
import org.apache.ibatis.session.SqlSession;
import utils.MyBatisUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by carryLess on 2017/11/29.
 */
public class StudentDaoImpl implements IStudentDao {
    private SqlSession sqlSession;


    @Override
    public void insertStudentByList(List<SStudent> studentList) {
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            sqlSession.insert("insertStudentByList", studentList);
            sqlSession.commit();
        }finally {
            //關閉sqlSession
            if(sqlSession != null){
                sqlSession.close();
            }
        }
    }

    @Override
    public SStudent selectById1(int id) {
        SStudent sStudent;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            sStudent = sqlSession.selectOne("selectById1", id);
        } finally {
            if(sqlSession != null){
                sqlSession.close();
            }
        }
        return sStudent;
    }

    @Override
    public SStudent selectById2(int id) {
        SStudent sStudent;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            sStudent = sqlSession.selectOne("selectById2", id);
        } finally {
            if(sqlSession != null){
                sqlSession.close();
            }
        }
        return sStudent;
    }
}

5.工具類

package utils;

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.InputStream;

/**
 * Created by carryLess on 2017/11/30.
 */
public class MyBatisUtils {

    /*
    * SqlSession 由SqlSessionFactory對象創建,
    * 而SqlSessionFactory對象為重量級對象
    * 並且是線程安全的,所以我們將其設為單例
    * */
    private static SqlSessionFactory factory;

    /**
     * 私有化構造方法,避免該工具類在外部被實例化
     */
    private MyBatisUtils(){}

    /**
     * 獲取 SqlSession
     * @return
     */
    public static SqlSession getSqlSession(){
        try {
            if(factory == null){
                //讀取配置文件
                InputStream inputStream = Resources.getResourceAsStream("mybatis.xml");
                //創建工廠類
                factory = new SqlSessionFactoryBuilder().build(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        /*
        * factory.openSession(true);     創建一個有自動提交功能的SqlSession
        * factory.openSession(false);    創建一個沒有自動提交功能的SqlSession,需要手動提交
        * factory.openSession();         同factory.openSession(false);
        */
        return factory.openSession();
    }
}

6.測試類

package test;

import dao.IStudentDao;
import dao.StudentDaoImpl;
import model.SStudent;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by carryLess on 2017/11/29.
 */
public class MyTest {

    private IStudentDao dao;

    @Before
    public void initDao(){
        dao = new StudentDaoImpl();
    }

    @Test
    public void testInsertList(){
        List<SStudent> sStudentList = new ArrayList<SStudent>();
        for(int i = 11;i<20;i++){
            SStudent sStudent = new SStudent();
            sStudent.setSname("zhangs-"+i);
            sStudent.setSage(25+i);
            sStudent.setScore(90);
            sStudentList.add(sStudent);
        }
        dao.insertStudentByList(sStudentList);
    }

    @Test
    public void testSelectById(){
        SStudent sStudent = dao.selectById2(18);
        System.out.println(sStudent);
    }


}

MyBatis_Study_003(字段名與屬性名稱不一致,resultMap)