MyBatis的優化

1 抽取MyBatisUtil

其中的sessionFactory必須用同一個對象,不然會空指針異常!

public enum MyBatisUtil {
    INSTANCE;

    private static SqlSessionFactory sessionFactory = null;

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

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

2 提取db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcdemo?useSSL=false
usename=root
password=111111

3 配置類型別名

<?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" />
    <!-- 爲類型起別名 -->
    <typeAliases>
        <typeAlias type="cn.itsource.shopping.domain.Product" alias="Product" />
    </typeAliases>
    <!-- 環境配置 -->
    <environments default="development">
        <!-- 連接數據的基本信息 -->
        <environment id="development">
            <!-- 事務管理器:JDBC的管理機制 -->
            <transactionManager type="JDBC" />
            <!-- 配置連接池(數據源) -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${usename}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- 關聯映射文件 -->
    <mappers>
        <mapper resource="cn\itsource\shopping\domain\ProductMapper.xml" />
    </mappers>
</configuration>

4 列名和屬性名不同

當屬性名和數據庫中的列名不同的時候,可以使用resultMap設置property=”字段名” column=”列名”其中的數據庫中的名稱不分大小寫,字段中的名稱嚴格區分大小寫!

<?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">
 <!-- 映射Product對象和對應表關係的,操作該表/對象的SQL全部都寫在這裏 -->
<mapper namespace="cn.itsource.shopping.mapper.ProductMapper">
    <!-- 裏面寫SQL -->
    <!-- 
        id:唯一的標識,和namespace組成全局的唯一名稱
        cn.itsource.shopping.mapper.ProductMapper.list
        parameterType:方法的參數類型
        resultType:返回類型,表中一行記錄對應的對象
     -->

    <!-- 查詢所有 -->
    <select id="list" resultMap="productMapping">
        SELECT * FROM product
    </select>

    <!-- 查詢單個 -->
    <!-- 裏面的參數爲什麼用小long:因爲基本類型的別名前面都是小寫 -->
    <select id="get" parameterType="long" resultType="Product">
        SELECT * FROM product where id = #{id}
    </select>

    <!-- 插入操作  -->
    <insert id="save" parameterType="Product" useGeneratedKeys="true" keyProperty="id">
        insert into product (productName,brand,supplier,salePrice,costPrice,cutoff,dir_id)
        values(#{productName},#{brand},#{supplier},#{salePrice},#{costPrice},#{cutoff},#{dir_id})
    </insert>

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

    <!-- 刪除操作 -->
    <delete id="delete" parameterType="long">
        delete from product where id = #{id}
    </delete>

    <!-- 解決屬性名列名不同的問題 -->
    <!-- 結果映射 -->
    <resultMap type="Product" id="productMapping">
        <!-- 映射主鍵列 -->
        <id property="id" column="id"/>
        <!-- 映射非主鍵列 -->
        <result property="productName" column="productName"/>
    </resultMap>
</mapper>

DAO

public class ProductDAOImpl implements IProductDAO {

    public void save(Product pro) {
        SqlSession session = MyBatisUtil.INSTANCE.openSession();
        try {
            session.insert("cn.itsource.shopping.mapper.ProductMapper.save", pro);
            session.commit();
        } finally {
            session.close();
        }
    }

    public void delete(Long id) {
        SqlSession session = MyBatisUtil.INSTANCE.openSession();
        try {
            session.update("cn.itsource.shopping.mapper.ProductMapper.delete", id);
            session.commit();
        } finally {
            session.close();
        }
    }

    public void update(Product pro) {
        SqlSession session = MyBatisUtil.INSTANCE.openSession();
        try {
            session.update("cn.itsource.shopping.mapper.ProductMapper.update", pro);
            session.commit();
        } finally {
            session.close();
        }
    }

    public Product get(Long id) {
        SqlSession session = MyBatisUtil.INSTANCE.openSession();
        try {
            return session.selectOne("cn.itsource.shopping.mapper.ProductMapper.get", id);
        } finally {
            session.close();
        }
    }

    public List<Product> list() {
        SqlSession session = MyBatisUtil.INSTANCE.openSession();
        try {
            return session.selectList("cn.itsource.shopping.mapper.ProductMapper.list");
        } finally {
            session.close();
        }
    }

DAO的實現接口

import java.util.List;

import cn.itsource.shopping.domain.Product;

public interface IProductDAO {
    void save(Product pro);

    void delete(Long id);

    void update(Product pro);//long id 包裝進去product

    Product get(Long id);

    List<Product> list();
}

測試類

private IProductDAO dao = new ProductDAOImpl();
    @Test
    public void testSave() {
        Product pro = new Product();
        pro.setProductName("iphone9s");
        pro.setBrand("apple");
        pro.setSupplier("蘋果公司");
        pro.setSalePrice(new BigDecimal("7000"));
        pro.setCostPrice(new BigDecimal("2000"));
        pro.setCutoff(0.9);
        pro.setDir_id(3L);
        //pro.setId(12L);
        dao.save(pro);

        System.out.println(pro);
    }

    @Test
    public void testDelete() {
        dao.delete(24L);
    }

    @Test
    public void testUpdate() {
        Product pro = new Product();
        pro.setProductName("iphone5s");
        pro.setBrand("apple9s");
        pro.setSupplier("蘋果公司2");
        pro.setSalePrice(new BigDecimal("6000"));
        pro.setCostPrice(new BigDecimal("1000"));
        pro.setCutoff(0.8);
        pro.setDir_id(5L);
        pro.setId(25L);
        dao.update(pro);
    }

    @Test
    public void testGet() {
        Product pro = dao.get(25L);
        System.out.println(pro);
    }

    @Test
    public void testList() {
        List<Product> list = dao.list();
        for (Product p : list) {
            System.out.println(p);
        }
    }

商品類對象

public class Product {
    private Long id;
    private String productName;
    private String brand;
    private String supplier;
    private BigDecimal salePrice;
    private BigDecimal costPrice;
    private Double cutoff;
    private Long dir_id;//分類編號

    public Long getId() {
        return id;
    }
    public String getProductName() {
        return productName;
    }
    public String getBrand() {
        return brand;
    }
    public String getSupplier() {
        return supplier;
    }
    public BigDecimal getSalePrice() {
        return salePrice;
    }
    public BigDecimal getCostPrice() {
        return costPrice;
    }
    public Double getCutoff() {
        return cutoff;
    }
    public Long getDir_id() {
        return dir_id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public void setProductName(String productName) {
        this.productName = productName;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public void setSupplier(String supplier) {
        this.supplier = supplier;
    }
    public void setSalePrice(BigDecimal salePrice) {
        this.salePrice = salePrice;
    }
    public void setCostPrice(BigDecimal costPrice) {
        this.costPrice = costPrice;
    }
    public void setCutoff(Double cutoff) {
        this.cutoff = cutoff;
    }
    public void setDir_id(Long dir_id) {
        this.dir_id = dir_id;
    }
    public String toString() {
        return "Product [id=" + id + ", productName=" + productName + ", brand=" + brand + ", suppliet=" + supplier
                + ", salePrice=" + salePrice + ", costPrice=" + costPrice + ", cutoff=" + cutoff + ", dir_id=" + dir_id
                + "]";
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章