What is MyBatis

An excellent persistence layer frame. MyBatis uses XML to decouple SQL from programs for easy maintenance. MyBatis is cheap to learn and efficient to execute. The bottom layer is the encapsulation and extension of JDBC.

  • MyBtis website:https://mybatis.org/mybatis-3/zh/index.html
  • Making address:https://github.com/mybatis/mybatis-3/releases

Tips: The source code and data tables involved in this article can be obtained in the public number to recommend learning Java reply myBatisDemo.

The whole process of creating a MyBatis project

  1. Creating a database
  2. Create a data table (the table structure and data in this article are not complex)
  3. Creating A Maven-based Java project (as practiced in the previous section)
  4. The basic configuration of the project is complete to ensure that the project can connect to the database successfully
  5. Manipulate data from the data tables in the database through Java code in the project
  6. Completion of business functions, project launch (project release)

4 and 5 are the core content of this section. The last point is not the actual content of this section. After learning the SSM comprehensive framework, we will specially explain it, which is more suitable at that time.

Ensure that the project is connected to the database successfully

1. Create tabletv_series

A record is a simple record of a television series, including this information:

Tv_id: the primary key increases automatically and cannot be empty.

Tv_title: The name of the TV show, also known as the title, cannot be empty.

Tv_sub_title: Description of a TV series, or a promotional short book with a subtitle.

Tv_type: Types of TV dramas, including suspense, martial arts, rivers and lakes, love, court and country.

2. Create maven-based Java projects

After clicking the last Nnext button to create the project, the following prompt will appear in the lower right corner of the new IDE window. Remember to click the arrow marked here:

If you can see the information in the red box, it means that the project was built successfully. Can next work!

3. Complete the basic configuration of the project

The following figure is based on the completed project structure, with the necessary configuration added. You can compare it with your own new project. The arrows are all manually created:

Here do specific explanation, the operation steps are basically “routine”, ha ha

  1. Red cut head 1, need to do the work

    Create a directory, about the name of this directory and pay attention to, generally we are used to call domain, bean, entity, choose a can. All calss in this directory correspond to the table fields in the database. The fields in the data table are separated by underscores, so the variables in this class are named with humps.

    package com.javafirst.bean;
    
    /** * desc: entity * author weChat: studyingJava */
    public class TVSeriesBean {
    
        private int tvId;
        private String tvTitle;
        private String tvSubTitle;
        private int tvType;
    
        public int getTvId(a) {
            return tvId;
        }
    
        public void setTvId(int tvId) {
            this.tvId = tvId;
        }
    
        public String getTvTitle(a) {
            return tvTitle;
        }
    
        public void setTvTitle(String tvTitle) {
            this.tvTitle = tvTitle;
        }
    
        public String getTvSubTitle(a) {
            return tvSubTitle;
        }
    
        public void setTvSubTitle(String tvSubTitle) {
            this.tvSubTitle = tvSubTitle;
        }
    
        public int getTvType(a) {
            return tvType;
        }
    
        public void setTvType(int tvType) {
            this.tvType = tvType;
        }
    
        @Override
        public String toString(a) {
            return "TVSeriesBean prints information: \n{" +
                    "tvId=" + tvId +
                    ", tvTitle='" + tvTitle + '\' ' +
                    ", tvSubTitle='" + tvSubTitle + '\' ' +
                    ", tvType=" + tvType +
                    '} '; }}Copy the code

    SetXXX () and getXXX() methods are generated manually. In fact, there are some plug-ins that can be done automatically.

  2. Red cut head 2, need to do the work

    Create folders manually, usually named DAO, or you can define them as you like. All files in this package are of type interface, which is used to provide interfaces that operate on SQL statements that affect data in the database. This links the project to the database, but at this point, it is far from accessible.

    Example code for this class is as follows. Others can be extended based on the service:

    package com.javafirst.dao;
    
    import com.javafirst.bean.TVSeriesBean;
    
    import java.util.List;
    
    /** * desc: studyingJava * 

    * Author weChat: studyingJava */

    public interface TVSeriesDao { /** * Query a TV series by id **@param tvId * @return* / TVSeriesBean selectTVSeriesById(Integer tvId); /** * query all series **@return* / List<TVSeriesBean> selectTVSeriesAll(a); /** * Add a record (TV series) by field **@param title * @param subTitle * @param type */ void addTVSeriesOne(String title, String subTitle, int type); /** * Add a record (TV series) by object **@param tvSeriesBean */ void addTVSeriesObject(TVSeriesBean tvSeriesBean); } Copy the code
  3. Red cut head 3, need to do the work

    Create a new folder resources in the main directory, which is at the same level as Java. IDEA will be automatically recognized when creating the folder. We do not need to manually enter the name, and directly select Enter to create a successful folder.

  4. Red cut head 4, need to do the work

    On the basis of step 3, create a mapper folder under the Resources directory, and then create xxxmapper.xml. This file and the previous created xxxDao file is the corresponding, so try to keep the same name, when the project is complex, it can be identified at a glance, easy to maintain and understand. Create tvSeriesmapper.xml as follows:

    
            
    <! DOCTYPEmapper
            PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.javafirst.dao.TVSeriesDao">
    
    </mapper>
    Copy the code

    The only thing that needs to be changed is the namespace value in the mapper tag. This value is familiar to you. This value is the full path of the XXXdao we created earlier.

    The nodes in the mapper tag are the XML syntax of our daily operation table, including < SELECT >, < INSERT >,

    , < DELETE > tags, The contents of these tags are the SQL statements we studied in the section recommended to learn Java – Table manipulation. Sample code is provided later in this article.

  5. Red cut head 5, need to do the work

    After step 3, create mybatis-config. XML in the Resources directory. The name of this file is not fixed, but it is usually written with this name, because it is used to ensure that the myBatis framework can be configured to connect to the database and manipulate data. So there’s a lot of fixed configuration items in there. The sample code for this article is as follows:

    
            
    <! DOCTYPEconfiguration
            PUBLIC "- / / mybatis.org//DTD Config / 3.0 / EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
    
        <environments default="development">
            <! -- Development environment -->
            <environment id="development">
                <transactionManager type="JDBC"/>
                <dataSource type="POOLED">
                    <! -- Mysql driver -->
                    <property name="driver" value="com.mysql.jdbc.Driver"/>
                    <! -- Specify the port on which the database is open, the name of the database to connect to, and the encoding mode -->
                    <property name="url"
                              value="jdbc:mysql://localhost:3306/mybatis_demo? useUnicode=true&amp;characterEncoding=utf8"/>
                    <! Mysql > select * from 'mysql';
                    <property name="username" value="root"/>
                    <! Mysql > select * from 'mysql';
                    <property name="password" value="root"/>
                </dataSource>
            </environment>
    
        </environments>
    
        <mappers>
            <! Configure each mapper file -->
            <mapper resource="mapper/TVSeriesMapper.xml"/>
        </mappers>
    </configuration>
    Copy the code

    Again, the code here is basically a template, with only a few key changes to make.

    <! -- Specify the port on which the database is open, the name of the database to connect to, and the encoding mode -->
                    <property name="url"
                              value="jdbc:mysql://localhost:3306/mybatis_demo? useUnicode=true&amp;characterEncoding=utf8"/>
                    <! Mysql > select * from 'mysql';
                    <property name="username" value="root"/>
                    <! Mysql > select * from 'mysql';
                    <property name="password" value="root"/>
    Copy the code
    • Localhost :3306 = localhost:3306 = localhost:3306

    • Mybatis_demo is the name of the database we created earlier, which is the first step in the overall flow of this section;

    • Mysql > select * from ‘mysql’ where username = ‘mysql’;

    • The password value corresponds to your password for logging in to mysql;

  6. Red cut head 6, need to do the work

    XML file will be automatically generated after the project is successfully created, we need to do is to configure the dependency in the inside, this is to use the content we learned in the last section “recommend learning Java — Maven introduction”, small series here do mySql driver and Mybatis dependency configuration complete code as follows:

    
            
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.javafirst</groupId>
        <artifactId>TV_series</artifactId>
        <version>1.0</version>
    
        <! -- Comment it out for now -->
        <! -- <name>TV_series</name>-->
        <! -- &lt; ! &ndash; FIXME change it to the project's website &ndash; &gt; -->
        <! -- <url>http://www.example.com</url>-->
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
    
        <dependencies>
            <! -- Unit tests (added by default) -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.11</version>
                <scope>test</scope>
            </dependency>
    
            <! -- mySql driver -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.25</version>
            </dependency>
    
            <! -- Mybatis dependency -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.5.7</version>
            </dependency>
        </dependencies>
    
        <build>
            <pluginManagement><! -- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
                <plugins>
                    <! -- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                    <plugin>
                        <artifactId>maven-clean-plugin</artifactId>
                        <version>3.1.0</version>
                    </plugin>
                    <! -- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                    <plugin>
                        <artifactId>maven-resources-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.8.0</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>2.22.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>3.0.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-install-plugin</artifactId>
                        <version>2.5.2</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-deploy-plugin</artifactId>
                        <version>2.8.2</version>
                    </plugin>
                    <! -- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                    <plugin>
                        <artifactId>maven-site-plugin</artifactId>
                        <version>3.7.1</version>
                    </plugin>
                    <plugin>
                        <artifactId>maven-project-info-reports-plugin</artifactId>
                        <version>3.0.0</version>
                    </plugin>
                </plugins>
            </pluginManagement>
        </build>
    </project>
    Copy the code

    For example, you can search for configurations in the Maven repository mentioned in the previous section and add them here. This is where Maven comes in handy.

  7. Red cut head 7, need to do the work

    At this point, the basic configuration work is done, the rest is the business code and logic, the first six steps are basically done every time we create a project, you need to be familiar with the process.

    Here’s a little trick:

    Xxxmapper. XML and mybatis-config. XML can actually use the template function of IDEA, convenient and quick.

    Here we create a new generic package utils. For now we will just create mybatisutil.java.

    package com.javafirst.utils;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    /** * desc: MyBatis * 

    * Author weChat: studyingJava */

    public class MyBatisUtil { private static SqlSessionFactory sqlSessionFactory = null; static { String configXml = "mybatis-config.xml"; try { InputStream inputStream = Resources.getResourceAsStream(configXml); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch(IOException e) { e.printStackTrace(); }}public static SqlSession openSqlSession(a) { SqlSession sqlSession = null; if (null! = sqlSessionFactory) { sqlSession = sqlSessionFactory.openSession(); }else { String configXml = "mybatis-config.xml"; try { InputStream inputStream = Resources.getResourceAsStream(configXml); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); } catch(IOException e) { e.printStackTrace(); }}returnsqlSession; }}Copy the code

    The reason for this tool class is that we want to avoid duplicate code, for why we write this, you can check MyBatis official website.

Let’s start writing functional code, testing linked data, and the exciting time is coming!

4. Test link is successful

The core of this article is MyBatis, now we test whether MyBatis and database link is successful, the code is as follows:

@Test
public void testSqlConnection(a) {
    SqlSession sqlSession = MyBatisUtil.openSqlSession();
    System.out.println("Test MyBatis linked database driver:" + sqlSession.toString());
}
Copy the code

This code is used to create a new Java class, then write this code, unit test, the result as shown in the following figure, then the link is successful, indicating that the previous mybatis-config. XML configuration did not error.

Operational data sheet

The next step is to manipulate a table in the database. At the beginning of this article, we created a new table with no data in it. Now let’s do a query, then an insert, and then a full query to prove that we can manipulate the database through a Java project.

  1. Querying all Records

    Unit test Java as follows:

    /** * query all records */
    @Test
    public void testSelectTVSeriesAll(a) {
        SqlSession sqlSession = MyBatisUtil.openSqlSession();
        TVSeriesDao tvSeriesDao = sqlSession.getMapper(TVSeriesDao.class);
        List<TVSeriesBean> tvSeriesBeans = tvSeriesDao.selectTVSeriesAll();
        sqlSession.close();
    
        System.out.println("Query all Records (TV series) :" + tvSeriesBeans.size());
        for(TVSeriesBean tvSeries : tvSeriesBeans) { System.out.println(tvSeries); }}Copy the code

    The select statement in mapper. XML is as follows:

    <mapper namespace="com.javafirst.dao.TVSeriesDao">
    
        <! Select * from user where user >
        <select id="selectTVSeriesAll" resultType="com.javafirst.bean.TVSeriesBean">
            select * from tv_series
        </select>
    </mapper>
    Copy the code

    Note that the id here needs to be the same as the interface name defined in our xxxDao.

    The difference with SQL statements is that you no longer need to start with; At the end. If the result is as follows, it is correct.

  2. Add a record

    We use two ways to add records. One is to pass values through fields. One way is by creating objects; In both cases, we need to note that the tv_id in the table is the primary key, which is self-incremented, so we do not need to set the value for this field.

    The first way:

    /** * Add a record by field */
    @Test
    public void testAddTVSeriesOne(a) {
        SqlSession sqlSession = MyBatisUtil.openSqlSession();
        TVSeriesDao tvSeriesDao = sqlSession.getMapper(TVSeriesDao.class);
    
        tvSeriesDao.addTVSeriesOne("Legend of the Condor Heroes."."Jin Yong's martial arts classics, inherited forever.".1);
        sqlSession.commit();
        sqlSession.close();
    
        System.out.println("Record added successfully!");
    }
    Copy the code

    SqlSession.com MIT (), which is related to the transaction we learned before, is enabled by default in MySQL, so after inserting the record, we need to manually commit the transaction to work. The mybatisutil. Java utility class can also initialize SqlSession with a parameter that specifies the default auto-commit.

    sqlSession = sqlSessionFactory.openSession(true);
    Copy the code

    Insert tags in mapper files are as follows:

    <insert id="addTVSeriesOne">
        insert into tv_series (tv_title,tv_sub_title,tv_type) values (#{param1},#{param2},#{param3})
    </insert>
    Copy the code

    In the case of fields, it is recommended to use #{param+ number} for column values (also called parameters), otherwise you may encounter a pit.

    If the result is as follows, a record is inserted correctly. At this point, you can open Navicat to view the data in the table (screenshots are not shown here).

    The second way:

    The Java code is as follows

    /** * Add a record by object */
    @Test
    public void testAddTVSeriesObject(a) {
        SqlSession sqlSession = MyBatisUtil.openSqlSession();
        TVSeriesDao tvSeriesDao = sqlSession.getMapper(TVSeriesDao.class);
    
        TVSeriesBean tvSeriesBean = new TVSeriesBean();
        tvSeriesBean.setTvTitle("Tian Long Ba Bu");
        tvSeriesBean.setTvSubTitle("At the end of the Northern Song Dynasty, there were frequent border conflicts between Song and Liao, and a big conspiracy was coming quietly...");
        tvSeriesBean.setTvType(2);
    
        tvSeriesDao.addTVSeriesObject(tvSeriesBean);
        sqlSession.commit();
        sqlSession.close();
    
        System.out.println("Record added successfully! !");
    }
    Copy the code

    Insert tags in mapper files are as follows:

    <insert id="addTVSeriesObject">
        insert into tv_series (tv_title,tv_sub_title,tv_type) values (#{tvTitle},#{tvSubTitle},#{tvType})
    </insert>
    Copy the code

    Note that the parameter (column value) must be passed in the same way as the field value in the user-defined entity class; otherwise, a mapping exception will occur.

    At this point, we have added two records. Use our previous query all records test method to see if there are really two records, as shown in the following figure:

    Notice that? The odd problem is that the total number of records is correct, but each record is displayed as null, which is clearly not correct because we have overridden the toString() method.

    In mybatis-config. XML, we did not configure the hump matching switch, so we add the following code:

     <! -- Enable hump naming mapping -->
     <settings>
         <setting name="mapUnderscoreToCamelCase" value="true"/>
     </settings>
    Copy the code

    The query result is as follows:

    This is a beginner need to pay attention to a point, remember!

  3. Delete a record

    Add an interface to TVSeriesDao: void deleteTVSeriesBeanById(Integer tvId); , then add the following methods to the test class:

    /** * Delete a record based on ID */
     @Test
     public void testDeleteTVSeriesBeanById(a) {
         SqlSession sqlSession = MyBatisUtil.openSqlSession();
         TVSeriesDao tvSeriesDao = sqlSession.getMapper(TVSeriesDao.class);
    
         tvSeriesDao.deleteTVSeriesBeanById(2);
         sqlSession.commit();
         sqlSession.close();
    
         System.out.println("Deleting a record succeeded! !");
     }
    Copy the code

    This is not all. You need to add the following code to tvSeriesmapper.xml:

     <! -- Delete record based on ID -->
     <delete id="deleteTVSeriesBeanById">
         delete from tv_series where tv_id = #{tvId}
     </delete>
    Copy the code

    At this point, you can run the test method with the following result:You can verify the results by querying again or directly looking at the data of the tables in the database without mapping.

    If you are careful, have you noticed that after the preliminary work is done, the remaining operation mode is basically fixed, and the areas that need to be modified are streamlined?

  4. Modify the record

    In order to demonstrate this function, we will change the title of the remaining record to “The New Version of the Legend of the Condor Heroes”. The following is the complete example code: interface code

    /** * change the title by ID *@param tvId
     */
    void updateTVSeriesBeanTitleById(Integer tvId,String tvTitle);
    Copy the code

    Code in tvSeriesmapper.xml:

    <! -- Update records according to ID -->
    <update id="updateTVSeriesBeanTitleById">
        update tv_series set tv_title = #{param2} where tv_id = #{param1}
    </update>
    Copy the code

    Test method code:

    /** * Modify the specified record data */
    @Test
    public void testUpdateTVSeriesBeanTitleById(a) {
        SqlSession sqlSession = MyBatisUtil.openSqlSession();
        TVSeriesDao tvSeriesDao = sqlSession.getMapper(TVSeriesDao.class);
    
        tvSeriesDao.updateTVSeriesBeanTitleById(1."The New Legend of the Condor Heroes.");
        sqlSession.commit();
        sqlSession.close();
    
        System.out.println("Update a record succeeded! !");
    }
    Copy the code

    The result is as follows:At this point, open the database, or run the query again to see the result, which is our modified result.

Here, our basic add, delete, change and check have been practical operation again, this is the core content, about the early project configuration that set, their practical operation again, the process recorded, this is the core content of this section.

However, the operations in this section are all based on a single table, and the operation business is very simple. For example, there is no way to prove that the insertion of a data is successful, so can we return the primary key of the record after insertion? Deletion is also the same reason, because we can not check the database every time in real business, and in large projects, the records in the table may be tens of thousands of, it is not realistic to view, so the advanced content of MyBatis will be explained in the following chapters, we hurry up to improve the code ~~

conclusion

  • MyBatis is a framework, master its use process and advanced usage is a qualified Java engineer must
  • The previous learning of SQL knowledge to master, the content of this section is the same, knowledge linked
  • There is no shortcut to programming, just practice

Tips: The source code and data tables involved in this article can be obtained in the public number to recommend learning Java reply myBatisDemo. Xiaobian specially created a public number: recommend learning Java, share original Java content, welcome to search attention (attention is to send video tutorial), learn Java together, see you next time!