1. 程式人生 > >MyBatis兩種執行XXXMapper.xml配置檔案中SQL語句的方法

MyBatis兩種執行XXXMapper.xml配置檔案中SQL語句的方法

一、SqlSession單例模式類

package cn.mybatis.Sql;

import java.io.IOException;
import java.io.InputStream;



import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * SqlSessionFactory,單例模式
 * @author
cjc * */
public class MyBatisSqlSessionFactory { private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory getSqlSessionFactory(){ if(sqlSessionFactory == null){ InputStream inputStream; try { //使用 mybatis-config.xml 內的資訊建立了 SqlSessionFactory 物件
inputStream = Resources.getResourceAsStream("config/mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } return sqlSessionFactory; } public
static SqlSession openSession(){ return getSqlSessionFactory().openSession(); } }

二、實體類Student

package cn.mybatis.entity;

import java.util.Date;


public class Student {
    private Integer studId;
    private String name;
    private String email;
    private Date dob;
    public Integer getStudId() {
        return studId;
    }
    public void setStudId(Integer studId) {
        this.studId = studId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    @Override
    public String toString() {
        return "Student [studId=" + studId + ", name=" + name + ", email="
                + email + ", dob=" + dob + "]";
    }



}

三、StudentMapper.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">
<!-- namespace等於StudentMapper的全類限定名,
    使得我們可以利用介面來呼叫對映的SQL語句,注意sql語句的id必須和介面的方法名一致 -->
<mapper namespace="cn.mybatis.mapperInterface.StudentMapper">
    <resultMap type="Student" id="StudentResult">   <!-- 為什麼可以用Student,因為在mybatis-config檔案設定了別名 -->
        <id property="studId" column="stud_id" />
        <result property="name" column="name" />
        <result property="email" column="email" />
        <result property="dob" column="dob" />
    </resultMap>

    <select id="findAllStudents" resultMap="StudentResult">
        SELECT * FROM STUDENTS
    </select>

    <select id="findStudentById" parameterType="int" resultType="Student">
        SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB
        FROM STUDENTS WHERE STUD_ID=#{Id}
    </select>

    <insert id="insertStudent" parameterType="Student">
        INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
        VALUES(#{studId },#{name},#{email},#{dob})
    </insert>
</mapper>

四、StudentMapper.java 介面

package cn.mybatis.mapperInterface;

import java.util.List;

import cn.mybatis.entity.Student;


/**
 * 在ssm框架中,
 * @author cjc
 *
 */
public interface StudentMapper {
    List<Student> findAllStudents();
    Student findStudentById(Integer id);
    void insertStudent(Student student);
}

第一種方法:
前提:StudentMapper.xml的名稱空間namespace要等於StudentMapper.java的全類限定名;StudentMapper.xml的SQL語句的id要和StudentMapper.java的方法名一致、方法引數型別為 parameterType 對應值、方法返回值型別為 returnType 對應值
例如對findAllStudents進行對比,在第一種方法中,業務實現是這樣的:

    public List<Student> findAllStudents() {
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();

        try{
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

            return studentMapper.findAllStudents();
        }finally{
            sqlSession.close();
        }
    }

我們都知道介面是不能直接例項化的,但是注意到StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); 例項化了StudentMapper,使得業務實現可以通過studentMapper.findAllStudents(); 來執行StudentMapper.xml裡面id為findAllStudents的SQL語句。

第二種方法:
第二種方法不通過StudentMapper.java這個介面。自然,不通過這個介面,我們的StudentMapper.xml的namespace就沒有說要與StudentMapper.java這個介面的全類限定名一致,因為在第二種方法中,這個介面可以完全刪去,那怎樣才能執行StudentMapper.xml的對應id的SQL語句呢?

    public List<Student> findAllStudents() {
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();

        try{

            List<Student> studentList = sqlSession.selectList("cn.mybatis.mapperInterface.StudentMapper.findAllStudents");

            return studentList;
        }finally{
            sqlSession.close();
        }
    }

與第一種方法通過sqlSession.getMapper(StudentMapper.class) 方法不同的是,第二種方法是通過sqlSession.selectList("cn.mybatis.mapperInterface.StudentMapper.findAllStudents"); (其中”cn.mybatis.mapperInterface.StudentMapper.findAllStudents”是StudntMapper.xml的名稱空間+SQL id)來直接執行StudentMapper.xml的SQL語句的

這裡值得一提的是,雙引號裡面執行的是什麼SQL操作,sqlSession就要呼叫什麼方法,如圖:
這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

在進行sqlSession的insert操作的時候,要記得sqlSession.commit()操作