Mybatis learning 01

  A recent study java framework, just finished school mybatis based applications, so wrote this essay as a summary.

About a .Mybatis

  When first learning, learning is so explained mybatis framework document:

   MyBatis persistence framework is to support outstanding ordinary SQL queries, stored procedures and advanced mappings. MyBatis eliminates almost all of the retrieved manually set JDBC code and parameters and the result set. MyBatis uses a simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects, ordinary Java Objects) to database records in.

   Ok? Persistence framework? Eliminate all jdbc code? I first read this passage really look blinded, first persistence layer concept is the first time I heard, and then the elimination of jdbc code is also some misunderstanding, was thinking not to write sql statement it can operate the database. Now after completing basic part look back at these issues can be considered a have a preliminary knowledge.
  The first is the persistence layer, I searched the Internet some of the concepts, preliminary understood as follows: in the database and java object data conversion operation with each other middleware is called persistence layer, but also introduced another concept here orm (Object Relational Mapping) object-relational mapping, the object here refers java object, refers to the relationship in the data, the lasting effect layer is to be mapped (i.e. above conversion) between them.
  Understand the role of mybatis after we look at it in the implementation process will be more clearly understood up.

Two .Mybatis simple application process

  First introduced into the corresponding jar package (omitted here) in the project,

  1. Core Profile: sqlMapConfig.xml

    Mybatis new resources in the resource file package core profile: sqlMapConfig.xml, disposed in the configuration corresponding to the tab configuration file:

    properties tab redistribute resource files, such as the introduction db.properties jdbc file parameters;

    Output configuration settings tab portion of mybatis initialization function, such as the configuration log

    typeAliases tab to configure the types of aliases, such as references to the configuration file of a type you need to write absolute or relative path, such as a List collection to use, you need to fill in the quote at the java.util.List, However, some types of deep packet path, will be relatively cumbersome configuration, only the configuration alias introduced into the path to the type of packet here.

    environments label configuration environment, the environment here refers to the database environment, such environment may be a plurality of labels each representing a different database connection.

    mappers tag is arranged sql mapping file (will be mentioned later).

    These are the basic configuration sqlMapConfig.xml label, and there are a lot of labels not listed.

  2.sql mapping file

    Traditional database operation is performed in the dao layer and mybatis these operations are encapsulated, can be arranged only in the configuration file. Like the traditional way, but also to establish a dao interface, but do not write implementation class, here's sql mapping file is equivalent to the implementation class, as follows:

  

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE Mapper the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" "http://mybatis.org/dtd/mybatis mapper.dtd--3 " > 
<-! proxy agent represents the current scan namespace attribute namespace, 
    attribute value generally equal to the address of the interface class corresponding to the dao dao interface class    -> 
< Mapper namespace =" COM. demo.mapper.BookDao " > 

    < The 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>
    <!- <! -->// fuzzy query page
    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 tag of each operation, the corresponding interface method dao

  3. The code calls

  Because we only write dao interface and the corresponding configuration files, how to create objects (or no) to call these methods do.

  Here again divided into several steps:

  1. reads the configuration file (i.e. SqlMapConfig.xml)

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

 

  2. Create sqlSession factory object and instantiate sqlSession objects (sqlSession here for the heavyweight object encapsulates a lot of data, it can be viewed as a database connection object, repeating creation and destruction will cause a lot of resource consumption)

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

 

   3. sqlSession object call interface method

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

 

III. Finally,

  Because just learning Mybatis, so just introduced the use of part features, there are not a lot of features and functions mentioned (such as the use annotation mode), above, there are many omissions in the wrong place, learning is a constant mistake error correction and then grow of course, encourage each other.

 

Guess you like

Origin www.cnblogs.com/zengtao614/p/11357768.html