MyBatis的概述及使用

1.框架的概述

什么是框架,框架从何而来,为什么使用框架?

    框架:

    1.是一系列jar包,本质是对JDK功能的拓展

    2.框架是一组程序的集合,包含了一系列的最佳实践,作用是解决某个领域的问题。

不同框架的目的是解决不用领域的问题!

---------------------------------

最佳实践(Bast Propertice):实际上是无数程序员经历过无数次尝试之后,总结出来的处理特定问题的特定方法。

    如果把程序员的自由发挥看作是一种通往成功的途径,最佳实践就是其中最短路径,能极大的解放生产力。

最佳实践三要素:可读性,可维护性,可拓展性。

简单就是美:消除重复  化繁为简  简单必须可读,简单必须刻拓展  减少依赖,消除耦合

------------------------------------

WEB开发中的最佳实践:分层开发模式(技术层面的“分而治之”)

JAVAEE开发根据职责的纵向划分:变现层,业务层,持久层:

表现层:(Predentaion Layer):web/mvc负责处理与节目交互的相关操作(Struts2)

业务层:(Business Layer):service:负责复杂的业务逻辑计算和判断(Spring)

持久层:(Persistent Layer):dao:负责将业务逻辑数据进行持久化储存(Hibernate/MyBatis)

2 ORM思想和MyBatis框架概述

ORM对象关系映射(Object Relation Mapping 简称ORM/OR Mapping)

是一种为了解决面向对象与关系数据库存在的互不匹配的现象技术,简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将java程序中的对象自动持久化到关系数据库中,避免直接使用SQL语句对关系型数据库中的数据进行操作,减少代码编写量,提高产品质量。
ORM主要解决对象-关系的映射:

面向对象概念:面向关系概念
--------------------------
类               表
对象          表的行(记录)
属性          表的列(字段)

ORM的实现思想:

    将关系数据库中表中的记录映射为对象,以对象的形式展现,程序员可以把对数据的操作转化为对对象的操作,因此ORM的目的是为了方便开发人员以面向对象的思想来实现对数据库的操作。

ORM 采用元数据来描述对象-关系映射细节

    元数据通常采用XML格式,并且放在专门的对象-关系映射文件中。

目前流行的ORM框架:

    1.JPA:本身是一种ORM规范,不是ORM框架,由各大ORM框架提供实现

    2.Hibernate:目前最流行的ORM框架,设计灵巧,性能优秀,文档丰富

    3.MyBatis:本是apache的一个开源项目IBatis,提供的持久层框架包括SQL Maps和DAO,允许开发人员直接编写SQL等

MyBatis前世今生:

    MyBatis 本是Apache的一个开源项目IBatis,2010年这个项目有Apache sofware foundation 迁移到了Google code,并且改名为MyBatis,2013年11月迁移到Github。

IBatis一词源于"internet abatis"的组合,是一个基于java的持久层框架。
ibatis提供的持久层框架包括SQL MAPS 和 Access Object Dao.

MyBatis的优势:

    Mybatis  是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。

    Mybatis  消除了几乎所有的JDBC代码和参数的手工设置以及结果的检索。

    Mybatis  使用简单的XML或注解用于配置和映射,将接口和java的POJOS(Plain Old Object,普通的java对象)映射成数据库中的记录。![ORM思维图](https://img-blog.csdn.net/20180101211938063?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwMTYxNzA4/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)

3 准备工作

1.提供Product对象,IProductDAO,ProductDAOImpl(未实现),ProductDAOTest.
2.使用框架第一步:拷贝jar包。
    ①:MySQL驱动:mysql-connector-java-5.1.22-bin.jar
    ②:MyBatis的核心jar:mybatis-3.2.1.jar
    ③:MyBatis的依赖jar:MyBatis目录/lib中所有的jar.
       PS:commons-longging-1.1.1.jar其实可以不需要
       记得看文档来找答案:不丢人!
-----------------------------------------------------

MyBatis的主配置文件:

放在resources中的MyBatis-config.xml文件

在文档中找的,不过我已经填好了,文档就在MyBatis驱动包中的mybatis-3.4.1.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/jdbcdemo?useSSL=false" />
                <property name="username" value="root" />
                <property name="password" value="111111" />
            </dataSource>
        </environment>
    </environments>
    <!-- 关联映射文件 -->
    <mappers>
        <mapper resource="cn\itsource\shopping\domain\ProductMapper.xml" />
    </mappers>
</configuration>

XML映射文件对SqlSession对象的调用

<?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" resultType="cn.itsource.shopping.domain.Product">
        SELECT * FROM product
    </select>

    <!-- 查询单个 -->
    <select id="get" parameterType="long" resultType="cn.itsource.shopping.domain.Product">
        SELECT * FROM product where id = #{id}
    </select>

    <!-- 插入操作  -->
    <insert id="save" parameterType="cn.itsource.shopping.domain.Product">
        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="cn.itsource.shopping.domain.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>

</mapper>

日志文件的配置

Log4简介:

Log4j有三个主要组件:Loggers(记录器),Appenders(输出源)和Layouts(布局)。
            课简单理解为日志类别,日志要输出的地方和日志以何种形式输出,综合使用这三个组件可以轻松的
            记录信息的类型和级别,并可以在运行时控制日志输出的样式和位置

log4j.rootLogger=ERROR, stdout

log4j.logger.cn.itsource.shopping=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

4 操作步骤

无论是用过的Hibernate,MyBatis,操作步骤:

1.从配置文件(通常是XML配置文件中)得到sessionfactory(相当于DataSource)。

2.由sessionfactory  产生 session(相当于Connection,和Web中HttpSession无关)。

3.在session中完成对数据的增删改查和事务提交等。

4.用完之后关闭session。
//1.加载MyBatis-connfig.xml 获取SqlSessionFactory:DataSource
//2.使用SqlSessionFactory创建SqlSession对象:connection
//3.使用SqlSession完成CRUD,事务操作
//4.释放SqlSession
public class ProductDAOImpl implements IProductDAO {

    public void save(Product pro) {
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsReader("MyBatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.insert("cn.itsource.shopping.mapper.ProductMapper.save", pro);//切记此处的""里面只能写cn.itsource.shopping.mapper.ProductMapper.词
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delete(Long id) {
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsStream("MyBatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.update("cn.itsource.shopping.mapper.ProductMapper.delete", id);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(Product pro) {
        try {
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsStream("MyBatis-config.xml"));
            SqlSession sqlSession = sqlSessionFactory.openSession();
            sqlSession.update("cn.itsource.shopping.mapper.ProductMapper.update", pro);
            sqlSession.commit();
            sqlSession.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Product get(Long id) {
        try {
            InputStream config = Resources.getResourceAsStream("MyBatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            Product obj = sqlSession.selectOne("cn.itsource.shopping.mapper.ProductMapper.get", id);
            sqlSession.close();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Product> list() {
        try {
            InputStream config = Resources.getResourceAsStream("MyBatis-config.xml");
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(config);
            SqlSession session = sessionFactory.openSession();
            //namespace + id -->指定了唯一的一个SQL
            List<Product> list = session.selectList("cn.itsource.shopping.mapper.ProductMapper.list");
            session.close();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

实现接口:

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();

}

测试类

public class ProductDAOTest {

    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);
    }

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

    @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(22L);
        dao.update(pro);
    }

    @Test
    public void testGet() {
        Product pro = dao.get(6L);
        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
                + "]";
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章