mybatis開發(fā)dao的方法(原始dao開發(fā)+mapper代理開發(fā))

一.SqlSession使用范圍

1.SqlSessionFactoryBuilder

通過SqlSessionFactoryBuilder創(chuàng)建會話工廠SqlSessionFactory
SqlSessionFactoryBuilder當(dāng)作一個工具類使用即可,不需要使用單例管理SqlSessionFactoryBuilder
在需要創(chuàng)建SqlSessionFactory時候,只需要new一次SqlSessionFactoryBuilder 即可

2.SqlSessionFactory

通過SqlSessionFactory創(chuàng)建SqlSession使用單例模式管理SqlSessionFactory(工廠一旦創(chuàng)建,使用一個實例)
將來mybatis和spring整合后使用單例模式管理sqlSessionFactory

3.SqlSession

SqlSession是一個面向用戶(程序員)的接口
SqlSession中提供了很多操作數(shù)據(jù)庫的方法,例如:selectOne/selectList
sqlSession是線程不安全的,在SqlSession實現(xiàn)類中除了有接口中的方法(操作數(shù)據(jù)庫的方法)還有ukulel域?qū)傩?/p>

SqlSession最佳應(yīng)用場合在方法體內(nèi),定義成局部變量使用

二.原始dao開發(fā)方法(程序員只需要寫dao接口和dao實現(xiàn)類)

開發(fā)環(huán)境及配置文件:mybatis(增刪改查)入門程序 ——學(xué)習(xí)筆記

接口:AdminDao.java

package dao;

import cn.huan.mybatis.AdminBean;

/**
 * Created by 馬歡歡 on 2017/6/29.
 */
public interface AdminDao {
    /**
     * 根據(jù)id查詢用戶信息
     * @param id
     * @return
     * @throws Exception
     */
    public AdminBean findUserById(int id) throws Exception;

    /**
     * 添加用戶信息
     * @param adminBean
     * @throws Exception
     */
    public void insertUser(AdminBean  adminBean) throws Exception;

    /**
     * 刪除用戶信息
     * @param id
     * @throws Exception
     */

    public void deleteYser(int  id) throws Exception;


}

實現(xiàn):AdminDaoImpl.java

package dao;

import cn.huan.mybatis.AdminBean;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

/**
 * Created by 馬歡歡 on 2017/6/29.
 */
public class AdminDaoImpl implements AdminDao{
    //需要向dao實現(xiàn)類中注入SqlSessionFactory
    //這里通過構(gòu)造方法注入
    private SqlSessionFactory sqlSessionFactory;
    public AdminDaoImpl(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory = sqlSessionFactory;
    }
    public AdminBean findUserById(int id) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        AdminBean adminBean =sqlSession.selectOne("test.findUserById",id);
        sqlSession.close();
        return adminBean;
    }

    public void insertUser(AdminBean adminBean) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("test.insertUser",adminBean);
        sqlSession.commit();
        sqlSession.close();
    }

    public void deleteYser(int id) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("test.deleteUser",id);
        sqlSession.commit();
        sqlSession.close();
    }
}

映射文件:adminMap.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="test">
    <!--通過id查找用戶-->
    <select id="findUserById" parameterType="int" resultType="cn.huan.mybatis.AdminBean">
        SELECT * FROM admin WHERE a_id =#{a_id}
    </select>
    <!--模糊查詢-->
    <select id="findUserByName" parameterType="java.lang.String" resultType="cn.huan.mybatis.AdminBean">
        SELECT * FROM admin WHERE a_username LIKE '%${value}%'
    </select>
    <!--添加用戶-->
    <insert id="insertUser" parameterType="cn.huan.mybatis.AdminBean">
        <!--將插入數(shù)據(jù)的主鍵返回
        SELECT Last_insert_ID 得到剛插入的主鍵值 只適用與自增主鍵
        keyProperty :將查詢到主鍵值設(shè)置到parameterType指定的對象的那個屬性
        order:SELECT Last_insert_ID執(zhí)行順序,相對于insert語句來說它的執(zhí)行順序-->
        <selectKey keyProperty="a_id" order="AFTER" resultType="java.lang.Integer">
            SELECT LAST_INSERT_ID()
        </selectKey>
        INSERT INTO admin (a_nameid,a_username,a_password,a_trank)
        VALUES(#{a_nameid},#{a_username},#{a_password},#{a_trank})
    </insert>
    <!--刪除用戶 通過id-->
    <delete id="deleteUser" parameterType="java.lang.Integer">
        DELETE from admin where a_id =#{a_id}
    </delete>
    <!--更新用戶信息通過id-->
    <update id="updateUser" parameterType="cn.huan.mybatis.AdminBean">
        UPDATE admin set a_nameid=#{a_nameid},a_username=#{a_username},a_password=#{a_password},a_trank=#{a_trank} where a_id=#{a_id}
    </update>

</mapper>

測試:AdminTest.java

package dao;

import cn.huan.mybatis.AdminBean;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

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

/**
 * Created by 馬歡歡 on 2017/6/29.
 */
public class AdminTest {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    //測試前執(zhí)行
   public void setUp() throws IOException {
       //配置文件
       String resource = "mybatis-config.xml";
       //的到配置文件流
       InputStream inputStream =  Resources.getResourceAsStream(resource);
       //創(chuàng)建會話工廠
       sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   }
   @Test
   public void testFinUserById() throws Exception {
       AdminDao adminDao= new AdminDaoImpl(sqlSessionFactory);
       AdminBean adminBean1 =adminDao.findUserById(1);
       System.out.println(adminBean1);
   }
}

總結(jié)問題:
1.dao接口實現(xiàn)類方法總中存在大量的模板方法
2.在調(diào)用sqlSession方法時時將statement的id硬編碼了
3.調(diào)用sqlsession方法時傳入的變量,由于sqlsession方法使用泛型,即使變量傳錯也不提示,不利于開發(fā)。

三.mapper代理方法(我們只需要mapper接口(相當(dāng)于dao接口))

1.在mapper.xml中,namespace等于mapper接口地址

2.mapper.java接口中的方法名和mapper.xml中statement的id一致
3.mapper.java接口中的方法輸入?yún)?shù)類型和mapper.xml中statement的parameterType指定類型一致。
4.mapper.java接口中的方法返回值類型和mapper.xml中statement的resultType一致

1.接口:AdminMapper.java

package cn.mapper;

import cn.huan.mybatis.AdminBean;

/**
 * Created by 馬歡歡 on 2017/6/29.
 */
public interface AdminMapper {
    /**
     * 根據(jù)id查詢用戶信息
     * @param id
     * @return
     * @throws Exception
     */
    public AdminBean findUserById(int id) throws Exception;


2.映射文件:mapper.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="cn.mapper.AdminMapper">
    <!--通過id查找用戶-->
    <select id="findUserById" parameterType="int" resultType="cn.huan.mybatis.AdminBean">
        SELECT * FROM admin WHERE a_id =#{a_id}
    </select>

</mapper>

配置文件:mybatis-config.xml

<?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">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/sams?serverTimezone=UTC "></property>
                <property name="username" value="root"></property>
                <property name="password" value="root"></property>
            </dataSource>
        </environment>
    </environments>
    <!--加載映射文件-->
    <mappers>
        <mapper resource="mapper/adminMap.xml"></mapper>
        <mapper resource="mapper/mapper.xml"></mapper>
    </mappers>
</configuration>

測試類:AdminMapperTest.java

package cn.mapper;

import cn.huan.mybatis.AdminBean;
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 org.junit.Before;
import org.junit.Test;

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

/**
 * Created by 馬歡歡 on 2017/6/29.
 */
public class AdminMapperTest {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    //測試前執(zhí)行
   public void setUp() throws IOException {
       //配置文件
       String resource = "mybatis-config.xml";
       //的到配置文件流
       InputStream inputStream =  Resources.getResourceAsStream(resource);
       //創(chuàng)建會話工廠
       sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
   }
   @Test
   public void testFinUserById() throws Exception {
       SqlSession sqlSession = sqlSessionFactory.openSession();
       //創(chuàng)建AdminMapper對象,mybatis自動生成mapper代理對象
       AdminMapper adminMapper = sqlSession.getMapper(AdminMapper.class);
       //調(diào)用adminMapper的方法
       AdminBean adminBean = adminMapper.findUserById(2);
       System.out.println(adminBean);
   }
}

image.png

上一篇:mybatis(增刪改查)入門程序 ——學(xué)習(xí)筆記

文集:mybatis框架學(xué)習(xí)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容