1. 程式人生 > >javaWeb-MyBatis框架常用知識點詳解

javaWeb-MyBatis框架常用知識點詳解

1.如何配置MyBatis中xml檔案的提示約束,如圖:

這裡寫圖片描述

2.MyBatis使用的是日誌框架,來記錄日誌,要想檢視它底層到底執行的是什麼sql語句,得配置日誌檔案,log4j.properties,放置resources原始檔目錄中,

簡介:
    其中有三個主要的元件:Loggers(記錄器),Appenders(輸出源)和Layouts(佈局):
可簡單理解為日誌級別/日誌要輸出的地方/日誌以何種形式輸出。綜合使用這三個組
件可以輕鬆地記錄資訊的型別和級別,並可以在執行時控制日誌輸出的樣式和位置。
內容:
    //Loggers記錄器:輸出錯誤級別的,標準輸出
    log4j.rootLogger
=ERROR, stdout //列印包cn.itsource中的日誌 log4j.logger.cn.itsource=TRACE //日誌輸出的排版和佈局 log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

3.MyBatis的主配置檔案(MyBatis-config.xml名字自擬,應放在resources資料夾中,內容從中文PDF中尋找)講解:

<?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的管理機制 --> <transactionManager type="JDBC" /> <!-- 配置連線池(資料來源) --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/MyDataBase" /> <property name="username" value="root" /> <property name="password" value="1229341617lq" /> </dataSource> </environment> </environments> <mappers> <!-- 表的配置檔案,封裝了對錶的CRUD操作,最前面不需要加/ --> <mapper resource="com/itcast/oa/domain/ProductMapper.xml" /> </mappers> </configuration>

4.MyBatis的物件對映檔案(放置domain中)配置講解:

<?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/domain+表配置檔名,namespace + id唯一找到sql語句 -->
<mapper namespace="com.itcast.oa.mapper.ProductMapper">
    <!--
        id:                    唯一標識,和namespace組成全域性唯一標識
        resultType:            返回型別(DML操作沒有此屬性),表中一行記錄對應的物件型別 全限定名稱
        parameterType:         引數型別
        parameterMap:           已經廢除不用,常用parameterType
     -->

    <select id="list" resultType="com.itcast.oa.domain.Product">
        SELECT * FROM product
    </select>

    <select id="get" resultType="com.itcast.oa.domain.Product" parameterType="long">
        SELECT * FROM product WHERE id = #{id}
    </select>

    <insert id="save" parameterType="com.itcast.oa.domain.Product" >
        INSERT INTO product 
            (productName, supplier, salePrice, costPrice, dir_id, cutoff, brand)
        VALUES
            (#{productName}, #{supplier}, #{salePrice}, #{costPrice}, #{dir_id}, #{cutoff}, #{brand})
    </insert>

    <delete id="delete" parameterType="long">
        DELETE FROM product WHERE id = #{id}
    </delete>

    <update id="update" parameterType="com.itcast.oa.domain.Product">
        UPDATE product SET 
            productName = #{productName}, brand = #{brand}, costPrice = #{costPrice}, salePrice = #{salePrice}, cutoff = #{cutoff}, supplier=#{supplier}, dir_id = #{dir_id}
        WHERE
            id = #{id}
    </update>
</mapper>

5.MyBatis實現CRUD操作的常規步驟:

1.載入MyBatis-config.xml檔案,獲取SqlSessionFactory物件(執行緒安全的,執行期間建立一次即可):DataSource

2.使用SqlSessionFactory建立Session物件(執行緒不安全的,每一個執行緒中都應該有一份例項物件):Connection 

3.使用SqlSession完成CRUD和事務操作(DML操作需要commit提交事務)

4.釋放SqlSession
package com.itcast.oa.dao.impl;

import java.io.InputStream;
import java.util.List;

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 com.itcast.oa.dao.IProductDao;
import com.itcast.oa.domain.Product;

/**
 *           MyBatis常規步驟: 
 * 1.載入MyBatis-config.xml檔案,獲取SqlSessionFactory物件(執行緒安全的,執行期間建立一次即可):DataSource
 * 2.使用SqlSessionFactory建立Session物件(執行緒不安全的,每一個執行緒中都應該有一份例項物件):Connection 
 * 3.使用SqlSession完成CRUD和事務操作(DML操作需要commit提交事務)
 * 4.釋放SqlSession
 */
public class ProductDaoImpl implements IProductDao {

    @Override
    public int save(Product obj) {
        try {
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsReader("MyBatis-config.xml"));
            SqlSession session = sessionFactory.openSession();

            int effectRows = session.insert("com.itcast.oa.mapper.ProductMapper.save", obj);

            session.commit();
            session.close();

            return effectRows;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delete(Long id) {
        try {
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsReader("MyBatis-config.xml"));
            SqlSession session = sessionFactory.openSession();

            int effectRows = session.delete("com.itcast.oa.mapper.ProductMapper.delete", id);

            session.commit();
            session.close();

            return effectRows;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int update(Product obj) {
        try {
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsReader("MyBatis-config.xml"));
            SqlSession session = sessionFactory.openSession();

            int effectRows = session.update("com.itcast.oa.mapper.ProductMapper.update", obj);

            session.commit();
            session.close();

            return effectRows;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Product get(Long id) {
        try {
            // 1.利用ibatis中的Resources類,載入來自classPath路徑下的主配置檔案資訊,得到SessionFactory物件
            InputStream config = Resources
                    .getResourceAsStream("MyBatis-config.xml");
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                    .build(config);
            // 2.通過sessionFactory物件開啟session得到SqlSession物件
            SqlSession session = sessionFactory.openSession();
            // 3.利用sqlSession執行CRUD操作:namespace+id,找到sql語句,並在此設定引數
            Product pro = session.selectOne(
                    "com.itcast.oa.mapper.ProductMapper.get", id);
            // 4.關閉sqlSession資源
            session.close();

            return pro;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public List<Product> getAll() {
        try {
            // 1.利用ibatis中的Resources類,載入來自classPath路徑下的主配置檔案資訊,得到SessionFactory物件
            InputStream config = Resources
                    .getResourceAsStream("MyBatis-config.xml");
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                    .build(config);
            // 2.通過sessionFactory物件開啟session得到SqlSession物件
            SqlSession session = sessionFactory.openSession();
            // 3.利用sqlSession執行CRUD操作:namespace+id,找到sql語句
            List<Product> productList = session
                    .selectList("com.itcast.oa.mapper.ProductMapper.list");
            // 4.關閉sqlSession資源
            session.close();

            return productList;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

6.優化操作:

6.1:抽取MyBatis工具類MyBatisUtil.java:

package com.itcast.oa.util;

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

public enum MyBatisUtil {
    INSTANCE;

    private static SqlSessionFactory sessionFactory;

    static{
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("MyBatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SqlSession getSession(){
        return sessionFactory.openSession();
    }

}


CRUD操作為:


package com.itcast.oa.dao.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.itcast.oa.dao.IProductDao;
import com.itcast.oa.domain.Product;
import com.itcast.oa.util.MyBatisUtil;

/**
 *           MyBatis常規步驟: 
 * 1.載入MyBatis-config.xml檔案,獲取SqlSessionFactory物件(執行緒安全,執行期間建立一次即可):DataSource
 * 2.使用SqlSessionFactory建立Session物件(執行緒不安全的,每一個執行緒中都應該有一份例項物件):Connection 
 * 3.使用SqlSession完成CRUD和事務操作(DML操作需要commit提交事務)
 * 4.釋放SqlSession
 */
public class ProductDaoImpl implements IProductDao {

    @Override
    public int save(Product obj) {
        SqlSession session = null;
        try{
            session = MyBatisUtil.INSTANCE.getSession();
            int effectRows = session.insert("com.itcast.oa.mapper.ProductMapper.save", obj);
            session.commit();

            return effectRows;
        }finally{
            session.close();
        }
    }

    @Override
    public int delete(Long id) {
        SqlSession session = null;
        try{
            session = MyBatisUtil.INSTANCE.getSession();
            int effectRows = session.delete("com.itcast.oa.mapper.ProductMapper.delete", id);
            session.commit();

            return effectRows;
        }finally{
            session.close();
        }
    }

    @Override
    public int update(Product obj) {
        SqlSession session = null;
        try{
            session = MyBatisUtil.INSTANCE.getSession();
            int effectRows = session.update("com.itcast.oa.mapper.ProductMapper.update", obj);
            session.commit();

            return effectRows;
        }finally{
            session.close();
        }
    }

    @Override
    public Product get(Long id) {
        SqlSession session = null;
        try{
            session = MyBatisUtil.INSTANCE.getSession();
            Product pro = session.selectOne(
                    "com.itcast.oa.mapper.ProductMapper.get", id);

            return pro;
        }finally{
            session.close();
        }
    }

    @Override
    public List<Product> getAll() {
        SqlSession session = null;
        try{
            session = MyBatisUtil.INSTANCE.getSession();
            List<Product> productList = session
                    .selectList("com.itcast.oa.mapper.ProductMapper.list");

            return productList;
        }finally{
            session.close();
        }

    }


}

6.2:抽取db.properties檔案(放置resources原始檔夾中):

driverClassName=com.mysql.jdbc.Driver
uri=jdbc:mysql://localhost:3306/MyDataBase
username=root
password=1229341617lq

主配置檔案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>
    <!-- 引入db.properties檔案中的資料庫配置資訊 -->
    <properties resource="db.properties" />

    <!-- 環境配置 -->
    <environments default="development">
        <!-- 連線資料庫的基本資訊配置 -->
        <environment id="development">
            <!-- 事務管理器:JDBC的管理機制 -->
            <transactionManager type="JDBC" />
            <!-- 配置連線池(資料來源) -->
            <dataSource type="POOLED">
                <property name="driver" value="${driverClassName}" />
                <property name="url" value="${uri}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!-- 表的配置檔案,封裝了對錶的CRUD操作,最前面不需要加/ -->
        <mapper resource="com/itcast/oa/domain/ProductMapper.xml" />
    </mappers>
</configuration>

6.3:在主配置檔案中配置類型別名:

<typeAliases>
    <typeAlias type="com.itcast.oa.domain.Product" alias="Product"/>
</typeAliases>



此時物件配置檔案為:
<?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/domain+表配置檔名,namespace + id唯一找到sql語句 -->
<mapper namespace="com.itcast.oa.mapper.ProductMapper">
    <!--
        id                     :    唯一標識,和namespace組成全域性唯一標識
        resultType   :      返回型別(DML操作沒有此屬性),表中一行記錄對應的物件型別 全限定名稱
        parameterType:  引數型別
     -->

    <select id="list" resultType="Product">
        SELECT * FROM product
    </select>

    <select id="get" resultType="Product" parameterType="long">
        SELECT * FROM product WHERE id = #{id}
    </select>

    <insert id="save" parameterType="Product" >
        INSERT INTO product 
            (productName, supplier, salePrice, costPrice, dir_id, cutoff, brand)
        VALUES
            (#{productName}, #{supplier}, #{salePrice}, #{costPrice}, #{dir_id}, #{cutoff}, #{brand})
    </insert>

    <delete id="delete" parameterType="long">
        DELETE FROM product WHERE id = #{id}
    </delete>

    <update id="update" parameterType="Product">
        UPDATE product SET 
            productName = #{productName}, brand = #{brand}, costPrice = #{costPrice}, salePrice = #{salePrice}, cutoff = #{cutoff}, supplier=#{supplier}, dir_id = #{dir_id}
        WHERE
            id = #{id}
    </update>
</mapper>

6.4:當物件得屬性名和資料庫中的列名不同時,可用resultMap配置,在物件配置檔案中:

<resultMap type="Product"(類型別名)  id="ProductMapping">
    <!-- 對映主鍵列 -->
    <id property="id" column="id" />
    <!-- 對映非主鍵列,其他屬性和列名相同的可省略不配 -->
    <result property="productname"  column="productName" />
</resultMap>

物件配置檔案為:
<?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/domain+表配置檔名,namespace + id唯一找到sql語句 -->
<mapper namespace="com.itcast.oa.mapper.ProductMapper">
    <!--
        id                     :    唯一標識,和namespace組成全域性唯一標識
        resultType   :      返回型別(DML操作沒有此屬性),表中一行記錄對應的物件型別 全限定名稱
        parameterType:  引數型別
     -->

    <select id="list" resultType="ProductMapping">
        SELECT * FROM product
    </select>

    <select id="get" resultType="ProductMapping" parameterType="long">
        SELECT * FROM product WHERE id = #{id}
    </select>

    <insert id="save" parameterType="Product" >
        INSERT INTO product 
            (productName, supplier, salePrice, costPrice, dir_id, cutoff, brand)
        VALUES
            (#{productName}, #{supplier}, #{salePrice}, #{costPrice}, #{dir_id}, #{cutoff}, #{brand})
    </insert>

    <delete id="delete" parameterType="long">
        DELETE FROM product WHERE id = #{id}
    </delete>

    <update id="update" parameterType="Product">
        UPDATE product SET 
            productName = #{productName}, brand = #{brand}, costPrice = #{costPrice}, salePrice = #{salePrice}, cutoff = #{cutoff}, supplier=#{supplier}, dir_id = #{dir_id}
        WHERE
            id = #{id}
    </update>


    <resultMap type="Product" id="ProductMapping">
        <!-- 對映主鍵列 -->
        <id property="id" column="id" />
        <!-- 對映非主鍵列 -->
        <result property="productname" column="productName" />
    </resultMap>
</mapper>

7.MyBatis的中間資料型別,如圖:
這裡寫圖片描述

8.儲存時設定屬性,物件插入後自動生成id(自動獲取生成主鍵),在物件配置檔案的insert標籤中新增:

useGeneratedKeys=true
keyProperty=”id”