最近在学习java框架,刚好学完mybatis基础应用,所以写下这篇随笔作个总结。

一.Mybatis简介

  初次学习的时候,学习文档上是这么解释mybatis框架:

  MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除 了几乎所有的 JDBC 代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。

  嗯?持久层框架?消除所有jdbc代码?我第一次看这段话是真的一脸蒙蔽,首先持久层这个概念我也是第一次听说,然后对消除jdbc代码也有部分误解,当时在想不用写sql语句就能对数据库进行操作吗。现在学完基础部分后再回头看这些问题也算是有了一个初步的认知了。   首先是持久层,我在网上搜索了一些概念,初步理解如下:对数据库中的数据和java对象进行互相转换的操作中间件称为持久层,这里又要引入另一个概念orm(Object Relational Mapping)对象关系映射,这里的对象指的就是java对象,关系指的是数据中的数据,持久层的作用就是将他们之间进行映射(也就是上面的相互转换).   了解了mybatis的作用后我们在来看它的实现过程也会更加清晰易懂了。

二.Mybatis简单应用流程

  首先在项目中导入对应jar包(此处省略),

  1.核心配置文件:sqlMapConfig.xml

    在resources资源文件包下新建mybatis的核心配置文件:sqlMapConfig.xml,在该文件的configuration标签下配置对应的设置:

    properties标签配置引入外部资源文件,如引入jdbc参数的db.properties文件;

    settings标签配置mybatis的部分功能的初始化,如配置日志的输出

    typeAliases标签配置类型的别名,如若要在该配置文件中引用某个类型则需将其绝对路径或相对路径写入,如要用到List集合,则需要在引用处填入java.util.List,而有的类型包路径较深,配置就会相对麻烦,配置别名后只需要在此处引入该类型的包路径即可.

    environments标签配置环境,这里的环境指的是数据库环境,如可配置多个environment标签分别代表不同的数据库连接.

    mappers标签则是配置sql的映射文件(后面会提到).

    以上就是sqlMapConfig.xml基本配置标签了,还有很多标签没列出来。

  2.sql映射文件

    传统的对数据库操作是在dao层进行的,而mybatis则是对这些操作进行封装,只需在配置文件中配置即可。和传统方式一样,也要建立一个dao接口,但是不用写实现类了,这里的sql映射文件则相当于该实现类,如下:

  

<?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属性表示当前代理的命名空间,
    属性值一般情况下等于dao的接口类地址  相当于dao接口实现类   -->
<mapper namespace="com.demo.mapper.BookDao">

    <resultMap id="book_type" type="book">
        <id property="id" column="id" />
        <result property="bookname" column="bookname" />
        <result property="authorid" column="authorid" />
        <result property="price" column="price" />
        <result property="pubname" column="pubname" />
        <result property="pubtime" column="pubtime" />
        <result property="typeid" column="typeid" />
        <association property="bookType" javaType="bookType">
            <id property="typeId" column="typeid" />
            <result property="typeName" column="typename" />
        </association>
    </resultMap>

    <!--这里会有增删改查的标签-->

    <!---->
    <insert id="addBook" parameterType="book">
        insert into book values (null,#{bookname},#{authorid},#{price},#{pubname},#{pubtime},#{typeid})
    </insert>
    <!---->
    <delete id="deleteBook" parameterType="int">
        delete from book where id=#{a}
    </delete>
    <!---->
    <update id="updateBook" parameterType="book">
        update book set `bookname`=#{bookname} where id=#{id}
    </update>
    <!---->
    <select id="getBookList" resultType="book">
        select * from book
    </select>
    <!--//模糊分页查询-->
    <!--List<Book> getBookList1(Book book);-->
    <select id="getBookList1" parameterType="map" resultType="book">
        select * from book where bookname like "%"#{name}"%" limit #{start},#{size}
    </select>
    <!--//动态增-->
    <!--int activeAdd(Book book);-->
    <insert id="activeAdd" parameterType="book">
        insert into book
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="bookname!=null">
                bookname,
            </if>
            <if test="authorid!=null">
                authorid,
            </if>
            <if test="price!=null">
                price,
            </if>
            <if test="pubname!=null">
                pubname,
            </if>
            <if test="pubtime!=null">
                pubtime,
            </if>
            <if test="typeid!=null">
                typeid,
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="bookname!=null">
                #{bookname},
            </if>
            <if test="authorid!=null">
                #{authorid},
            </if>
            <if test="price!=null">
                #{price},
            </if>
            <if test="pubname!=null">
                #{pubname},
            </if>
            <if test="pubtime!=null">
                #{pubtime},
            </if>
            <if test="typeid!=null">
                #{typeid},
            </if>
        </trim>
    </insert>
    <!--//动态修改-->
    <!--int activeUpdate(Book book);-->
    <update id="activeUpdate" parameterType="book">
        update book
        <set>
          <if test="bookname!=null">
            bookname=#{bookname},
          </if>
            <if test="price!=null">
              price=#{price},
            </if>
            <if test="pubname!=null">
                pubname=#{pubname},
            </if>
            <if test="pubtime!=null">
                pubtime=#{pubtime},
            </if>
        </set>
        where id=#{id}
    </update>
    <!--//动态查询-->
    <!--List<Book> activeQuery(Map map);-->
    <select id="activeQuery" parameterType="map" resultType="book">
        select * from book
        <where>
            <if test="bookname!=null">
                and bookname like "%"#{bookname}"%"
            </if>
            <if test="price!=null">
                and price=#{price}
            </if>
            <if test="pubname!=null">
                and pubname=#{pubname}
            </if>
            <if test="pubtime!=null">
                and pubtime=#{pubtime}
            </if>
        </where>
        limit #{start},#{size}
    </select>
    <!--//动态查询2-->
    <!--List<Book> activeQuery2(Map map);-->
    <select id="activeQuery2" parameterType="map" resultType="book">
        select * from book
        <where>
            <if test="book.bookname!=null">
                and bookname like "%"#{book.bookname}"%"
            </if>
            <if test="book.price!=null">
                and price=#{book.price}
            </if>
            <if test="book.pubname!=null">
                and pubname=#{book.pubname}
            </if>
            <if test="book.pubtime!=null">
                and pubtime=#{book.pubtime}
            </if>
        </where>
        limit #{start},#{size}
    </select>
    <!--//联表查询: 多对1-->
    <!--Book QueryBook(int id);-->
    <select id="QueryBook" parameterType="int" resultMap="book_type">
        select * from book b inner join booktype bt on b.typeid=bt.typeid where id=#{a}
    </select>
</mapper> 

    每个操作标签的id则对应一个dao接口的方法

  3.代码中的调用

  因为dao我们只写了接口和对应的配置文件,那怎么来创建对象(或不需要)来调用这些方法呢.

  这里又要分为几个步骤:

  1.读取配置文件(即sqlMapConfig.xml)

InputStream rs = Resources.getResourceAsStream("sqlMapConfig.xml");

  2.创建sqlSession工厂对象并实例化sqlSession对象(这里的sqlSession为重量级对象,封装了很多数据,可看作是一个数据库连接对象,重复创建和销毁会造成大量资源占用)

SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory ssf = builder.build(rs);
sqlSession = ssf.openSession();

  3.用sqlSession对象调用接口中的方法

int i = sqlSession.getMapper(BookDao.class).deleteBook(11);

三.最后

  因为刚学Mybatis,所以只是介绍了部分功能特性的使用,还有很多特性和功能没提到(如注解方式的使用),上文也有很多疏漏错误的地方,学习就是一个不断犯错改错然后成长的过程,共勉。

优质内容筛选与推荐>>
1、使用Reaver加PIN码秒破WPA-PSK密码
2、第六章函数与宏定义实验报告(2)
3、jdbc初步(转)
4、keepalive方案
5、Node.js——环境变量


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn