mybatis開發dao方法

原始Dao開發方法

dao接口

package dao;

import po.Items;

import java.util.List;

/**
 * Created by admin on 2017/7/1.
 */
public interface ItemsDao {

    //根據id查詢商品信息
    public Items findItemsById(int id) throws Exception;

    //根據商品名列查詢商品列表
    public List<Items> findItemsByName(String name) throws Exception;

    //添加商品信息
    public void insertItems(Items items) throws Exception;

    //刪除商品信息
    public void deleteItems(int id) throws Exception;
}

dao接口實現類

package dao.impl;

import dao.ItemsDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import po.Items;

import java.util.List;

/**
 * Created by admin on 2017/7/1.
 */
public class ItemsDaoImpl implements ItemsDao {

    // 需要向dao實現類中注入SqlSessionFactory
    // 這里通過構造方法注入
    private SqlSessionFactory sqlSessionFactory;

    public ItemsDaoImpl(SqlSessionFactory sqlSessionFactory){
        this.sqlSessionFactory = sqlSessionFactory;
    }


    @Override
    public Items findItemsById(int id) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        Items items = sqlSession.selectOne("mapper.ItemsMapper.findItemsById", id);
        //釋放資源
        sqlSession.close();
        return items;
    }

    @Override
    public List<Items> findItemsByName(String name) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Items> list = sqlSession.selectList("mapper.ItemsMapper.findItemsByName", name);
        //釋放資源
        sqlSession.close();
        return list;
    }

    @Override
    public void insertItems(Items items) throws Exception {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("mapper.ItemsMapper.insertItems", items);

        //提交事務
        sqlSession.commit();

        //釋放資源
        sqlSession.close();
    }

    @Override
    public void deleteItems(int id) throws Exception {

        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.delete("mapper.ItemsMapper.deleteItems",id);

        sqlSession.commit();
        sqlSession.close();
    }
}

映射文件ItensMapper.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 命名空間,作用就是對sql進行分類化管理,理解為sql隔離
 注意:使用mapper代理方法開發,namespace有特殊重要的作用
 -->
<mapper namespace="mapper.ItemsMapper">

    <!-- 通過select執行數據庫查詢
    id:標識映射文件中的sql,稱為statement的id
    將sql語句封裝到mappedStatement對象中,所以將id稱為statement的id
    parameterType:指定輸入參數的類型
    #{}標示一個占位符,
    #{value}其中value表示接收輸入參數的名稱,如果輸入參數是簡單類型,那么#{}中的值可以任意。

    resultType:指定sql輸出結果的映射的java對象類型,select指定resultType表示將單條記錄映射成java對象
    -->
    <!-- public List<Items> queryItemsById(Integer id);-->
    <select id="queryItemsById" parameterType="int" resultType="po.Items">
        SELECT * FROM items WHERE id = #{id}
    </select>

    <!--    public Items findItemsById(int id) throws Exception;-->
    <select id="findItemsById" parameterType="int" resultType="po.Items">
        SELECT * FROM items WHERE id = #{id}
    </select>

    <!-- 根據商品名稱模糊查詢商品信息,可能返回多條
    resultType:指定就是單條記錄所映射的java對象類型
    ${}:表示拼接sql串,將接收到參數的內容不加任何修飾拼接在sql中。
    使用${}拼接sql,引起 sql注入
    ${value}:接收輸入參數的內容,如果傳入類型是簡單類型,${}中只能使用value
     -->
    <!--    public List<Items> findItemsByName(String name) throws Exception;-->
    <select id="findItemsByName" parameterType="string" resultType="po.Items">
        SELECT * FROM items WHERE name LIKE '%#{name}%'
    </select>
    
    <!--    public void insertItems(Items items) throws Exception;-->
    <select id="insertItesm" parameterType="po.Items">
        INSERT INTO items(name, price, detail, pic) VALUES (#{name},#{price},#{detail},#{pic})
    </select>

    <!--    public void deleteItems(int id) throws Exception;-->
    <select id="deleteItems" parameterType="int">
        DELETE FROM items WHERE  id = #{id}
    </select>
</mapper>

測試類Test02.java

package test;

/**
 * Created by admin on 2017/7/1.
 */
public class Test02 {

    private SqlSessionFactory sqlSessionFactory;
    // 此方法是在執行testFindUserById之前執行
    @Before
    public void setUp() throws IOException {
        // 創建sqlSessionFactory

        // mybatis配置文件
        String resource = "SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);

        // 創建會話工廠,傳入mybatis的配置文件信息
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @org.junit.Test
    public void testFindItemsById() throws Exception {

        //創建ItemsDao對象
        ItemsDao itemsDao = new ItemsDaoImpl(sqlSessionFactory);

        //調用ItemsDao方法
        Items itemsById = itemsDao.findItemsById(2);

        System.out.println(itemsById);
    }
}

運行結果

圖片.png

總結原始dao開發問題

1.dao接口實現類方法中存在大量模板方法,設想能否將這些代碼提取出來,大大減輕程序員的工作量。

2.調用sqlsession方法時將statement的id硬編碼了

3.調用sqlsession方法時傳入的變量,由于sqlsession方法使用泛型,即使變量類型傳入錯誤,在編譯階段也不報錯,不利于程序員開發。

mapper代理方法

程序員只需要mapper接口(相當 于dao接口)

程序員還需要編寫mapper.xml映射文件

程序員編寫mapper接口需要遵循一些開發規范,mybatis可以自動生成mapper接口實現類代理對象。

開發規范

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

<!--
 namespace 命名空間,作用就是對sql進行分類化管理,理解為sql隔離
 注意:使用mapper代理方法開發,namespace有特殊重要的作用
 -->
<mapper namespace="mapper.ItemsMapper">
  • mapper.java接口中的方法名和mapper.xml中statement的id一致
  • mapper.java接口中的方法輸入參數類型和mapper.xml中statement的parameterType指定的類型一致。
  • mapper.java接口中的方法返回值類型和mapper.xml中statement的resultType指定的類型一致。
<select id="findItemsById" parameterType="int" resultType="po.Items">
        SELECT * FROM items WHERE id = #{id}
    </select>
    //根據id查詢商品信息
    public Items findItemsById(int id) throws Exception;

以上開發規范主要是對下邊的代碼進行統一生成:

 SqlSession sqlSession = sqlSessionFactory.openSession();
        Items items = sqlSession.selectOne("mapper.ItemsMapper.findItemsById", id);

代碼部分

圖片.png
可以在配置文件新建一個同樣的mapper文件夾放映射文件,這樣就可以和java代碼分開

ItemsMapper.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="mapper.ItemsMapper">

    <!-- public List<Items> queryItemsById(Integer id);-->
    <select id="queryItemsById" parameterType="int" resultType="po.Items">
        SELECT * FROM items WHERE id = #{id}
    </select>

    <!--    public Items findItemsById(int id) throws Exception;-->
    <select id="findItemsById" parameterType="int" resultType="po.Items">
        SELECT * FROM items WHERE id = #{id}
    </select>

    <!--    public List<Items> findItemsByName(String name) throws Exception;-->
    <select id="findItemsByName" parameterType="string" resultType="po.Items">
        SELECT * FROM items WHERE name LIKE '%#{name}%'
    </select>
    
    <!--    public void insertItems(Items items) throws Exception;-->
    <select id="insertItesm" parameterType="po.Items">
        INSERT INTO items(name, price, detail, pic) VALUES (#{name},#{price},#{detail},#{pic})
    </select>

    <!--    public void deleteItems(int id) throws Exception;-->
    <select id="deleteItems" parameterType="int">
        DELETE FROM items WHERE  id = #{id}
    </select>
</mapper>

SqlMapConfig.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">
            <!-- 使用jdbc事務管理,事務控制由mybatis-->
            <transactionManager type="JDBC"/>
            <!-- 數據庫連接池,由mybatis管理-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis001"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
   <mappers>
        <mapper resource="mapper/ItemsMapper.xml"/>
    </mappers>
</configuration>

ItemsMapper.java

package dao;

import po.Items;

import java.util.List;

/**
 * Created by admin on 2017/7/1.
 */
public interface ItemsMapper{

    //根據id查詢商品信息
    public Items findItemsById(int id) throws Exception;

    //根據商品名列查詢商品列表
    public List<Items> findItemsByName(String name) throws Exception;

    //添加商品信息
    public void insertItems(Items items) throws Exception;

    //刪除商品信息
    public void deleteItems(int id) throws Exception;
}

Test03.java

package test;

import dao.ItemsDao;
import dao.impl.ItemsDaoImpl;
import mapper.ItemsMapper;
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.*;
import po.Items;

import java.io.InputStream;

/**
 * Created by admin on 2017/7/1.
 */
public class Test03 {
    private SqlSessionFactory sqlSessionFactory;
    //注解Before是在執行本類所有測試方法之前先調用這個方法
    @Before
    public void setup() throws Exception{
        //創建SqlSessionFactory
        String resource="SqlMapConfig.xml";
        //將配置文件加載成流
        InputStream inputStream = Resources.getResourceAsStream(resource);

        //創建會話工廠,傳入mybatis配置文件的信息
        sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
    }

    @org.junit.Test
    public void testFindItemsById() throws Exception{
        SqlSession sqlSession=sqlSessionFactory.openSession();

        //創建ItemsDao代理對象
        ItemsMapper mapper = sqlSession.getMapper(ItemsMapper.class);

        //調用userMapper的方法
        Items items =mapper.findItemsById(1);
        System.out.println(items.getName());
    }
}

運行結果
圖片.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容