Introduction and use of MyBatis framework (the children next door will talk about it) -- Basic

1: Overview

         MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures and advanced mapping. MyBatis eliminates almost all the manual setting of JDBC code and parameters and the retrieval of result sets. MyBatis uses simple XML or annotations for configuration and original mapping, and maps interfaces and Java POJOs (Plain Ordinary Java Objects) into records in the database

2: Features and working principle:


  • Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation is as long as two jar files + several sql mapping files are configured. It is easy to learn and use. You can fully master its design idea and implementation through documents and source code.

  • Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. All requirements for operating the database can be met through sql statements.

  • Decouple sql and program code: by providing DAO layer, separate business logic and data access logic, so as to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.

  • Provide mapping labels to support the mapping of orm fields between objects and databases

  • Provide object relationship mapping labels to support object relationship construction and maintenance

  • Provide xml tags to support writing dynamic sql

working principle:

3: Use

        1: Create a Maven project

  ② Click finish to complete the creation

  ③ The pom.xml file should maintain the following settings to facilitate the introduction of jar packages later

  2: Prepare a data table. I use the mysql data table here (the table name is book_info)

  3: Import mybatis jar package and create mybatis configuration file

① : import the jar package and click refresh in the upper right corner to save

  ② Create the following files in the resources directory. The suffix of the file is. xml (very important, it must be included)

4: Introduce mysql jar package into pom.xml file and create file to connect to database

① Introducing mysql jar package

  ② Create the file and fill in the following

  5: Write the following code in the mybatis.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-// Config 3.0//EN"
    <properties resource=""></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}" />
                <property name="url" value="${jdbc.url}" />
                <property name="username" value="${jdbc.username}" />
                <property name="password" value="${jdbc.password}" />

  6: Create book entity class

  7: Create BookDao interface and operation method of database

What I write here is the addition, deletion and modification of the database, which is checked and queried according to the id

  8: Create the mapper directory and the BookMapper.xml mapping file in the resources directory

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN"

  9: Write relevant code in the mapping file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.zhu.dao.BookDao">
    <resultMap id="my" type="com.zhu.entity.Book">
        <id column="book_id" property="id"></id>
        <result column="book_name" property="name"></result>
        <result column="book_author" property="author"></result>
        <result column="book_price" property="price"></result>
        <result column="book_pub" property="pub"></result>
    <!--Add data-->
    <insert id="insert">
        insert into book_info values(null,#{name},#{author},#{price},#{pub})
    <!--Modify data-->
    <update id="update">
        update book_info set book_name=#{name},book_author=#{author},book_price=#{price},book_pub=#{pub} where book_id=#{id}
    <!--Delete data-->
    <delete id="delete">
        delete from book_info where book_id=#{id}
    <!--according to id Find data-->
    <select id="findById" resultMap="my">
        select * from book_info where book_id=#{id}
    <!--Find all data-->
    <select id="findAll" resultMap="my">
        select * from book_info

  9: Add a mapping file to the configuration file

        <mapper resource="mapper/BookMapper.xml"></mapper>

10: Writing test classes

① : add a data entry to the database  


  ② Delete


③ Renew

Table before update:

After update:


  ④ Find by id

⑤ Find all



import com.zhu.dao.BookDao;
import com.zhu.entity.Book;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class BookTest {
    SqlSession session = null;
    public void before() throws Exception{
        Reader reader = Resources.getResourceAsReader("mybatis.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(reader);
    public void insertTest(){
        BookDao mapper = session.getMapper(BookDao.class);
        Book book = new Book("The Plum in the Golden Vase", "Unknown", 99, "xx press");
        int row = mapper.insert(book);
        System.out.println("Number of rows affected:"+row);
    public void deleteTest(){
        BookDao mapper = session.getMapper(BookDao.class);
        int row = mapper.delete(1004);
        System.out.println("Number of rows affected:"+row);
    public void updateTest(){
        BookDao mapper = session.getMapper(BookDao.class);
        Book book = new Book(1007, "Romance of the Three Kingdoms", "Luo Guanzhong", 108, "Renmin University Press");
        int row = mapper.update(book);
        System.out.println("Number of rows affected:"+row);
    public void findById(){
        BookDao mapper = session.getMapper(BookDao.class);
        Book byId = mapper.findById(1005);
    public void findAll(){
        BookDao mapper = session.getMapper(BookDao.class);
        List<Book> list = mapper.findAll();

The above is about the basic operation of mybatis on the database


Tags: Java MySQL Maven Mybatis

Posted on Fri, 03 Dec 2021 10:11:03 -0500 by gasxtreme