The second part of MyBatis series: building Maven project operation database table

1, ORMpping interpretation

ORMpping: object relationship mapping.

Object: refers to the object in Java, object-oriented thinking; relationship: refers to the relational database, here refers to the MySQL database. For the mapping of Java objects to MySQL tables, developers can manage the database in an object-oriented way.

2, Create Maven project and introduce pom dependency (project structure at initialization time)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""


        <!--MyBatis rely on-->
        <!--MySQL Connection dependency-->
        <!--lombok Plug in dependency-->

    <!--Fewer files are compiled mapper.xml,This and maven of maven compile src/java When coding, only the java The file is compiled and then placed in the target/classes Directory, need to be in pom.xml Add the following configuration to-->
    <!--If you do not add this node, mapper.xml Documents Documents config.spring No files will be loaded into target Of classes In the middle, it can't be used, and it will report an error-->


3, New database table

show databases;
show tables;
select * from RUN_User;
desc RUN_User;
show create table RUN_User;
  `Id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'Primary key,user Id',
  `Name` varchar(32) NOT NULL DEFAULT '' COMMENT 'full name',
  `Age` smallint(6) NOT NULL DEFAULT '1' COMMENT 'Age',
  `Salary` decimal(12,2) NOT NULL DEFAULT '0.00' COMMENT 'salary',
  `Sex` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Gender:0=unknown,1=male,2=female',
  `Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1=Effective,-1=invalid',
) ENGINE=InnoDB COMMENT='User table';

4, New Java entity class

public class UserEntity implements Serializable {
    private static final long serialVersionUID = -8951521178221206271L;
    private long id;            //Primary key, user Id
    private String name;        //full name
    private int age;            //Age
    private double salary;      //salary
    private int sex;            //Gender: 0 = unknown, 1 = male, 2 = female
    private int status;         //1 = valid, - 1 = invalid
    private Date addTime;       //Add time
    private Date updateTime;    //Update time

5, Create MyBatis configuration file for mybatis-config.xml , file name can be customized

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

        <package name="com.wind.entity"/>

    <!--to configure mybatis Operating environment-->
    <environments default="development">
        <environment id="development">
            <!--to configure JDBC transaction management-->
            <transactionManager type="JDBC"></transactionManager>
            <!--to configure POOLED Of type JDBC Data source connection pool-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url"
                <property name="username" value="root"/>
                <property name="password" value="admin0001112"/>

    <!--register mapper file-->
        <mapper resource="com/entity/mapper/UserMapper.xml"/>


6, Using MyBatis native interface mode

The MyBatis framework requires developers to define their own SQL statements, which are written in Mapper.xml File. In actual development, corresponding entity classes will be created for each table Mapper.xml File, which defines the SQL to manage the object data.

1. Definition UserMapper.xml File is used to manage RUN_User table

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

    <resultMap id="userMap" type="com.wind.entity.UserEntity">
        <id column="Id" property="id"/>
        <result column="Name" property="name"/>
        <result column="Age" property="age"/>
        <result column="Salary" property="salary"/>
        <result column="Sex" property="sex"/>
        <result column="Status" property="status"/>
        <result column="AddTime" property="addTime"/>
        <result column="UpdateTime" property="updateTime"/>

    <sql id="sql_select">
        select Id, Name, Age, Salary, Sex, Status, AddTime, UpdateTime from RUN_User

    <insert id="insertUser" parameterType="userEntity" useGeneratedKeys="true"
        insert into RUN_User ( Name, Age, Salary, Sex, Status )
        values ( #{name}, #{age}, #{salary}, #{sex}, 1 )



(1) Namespace: the namespace, which is usually set to the package where the file is located + the file name.

(2) The insert, update, delete, and select tags are used to define the operations of adding, modifying, and deleting database tables.

(3) id: the parameter needed to actually call MyBatis mode.

(4) Parameter: the type of parameter required when calling the corresponding method.

(5) useGeneratedKeys: used to enable whether to return the primary key ID after inserting a piece of data. If it is true, it is enabled, and the primary key ID will be returned to the java program on the keyProperty tag mapped.

2. Register in MyBatis profile UserMapper.xml file

   <!--register mapper file-->
        <mapper resource="com/entity/mapper/UserMapper.xml"/>

3. Mode 1: call the MyBatis native interface to perform the insertion operation

public class UserTest {

    public static void main(String[] args) {
        //Load MyBatis profile
        InputStream inputStream = UserTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory =;
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //A specific method of locating to Mapper file
        String statement = "com.entity.mapper.UserMapper.insertUser";
        UserEntity userEntity = new UserEntity("Wenbixia", 31, 5000.9, 2);
        int result = sqlSession.insert(statement, userEntity);


If such an error is reported, it means that our Maven project has not actively read the XML file under the java package and put it into the class file under the target. At this time, we need to pom.xml The resource tag is additionally configured in the file.

The resource label is as follows:

    <! -- fewer files are compiled mapper.xml This is related to maven. When maven compiles src/java code, it only compiles java files by defau lt and then places them in the target/classes directory pom.xml Add the following configuration -- >
    <! -- if you do not add this node, mapper.xml Documents Documents config.spring The file will not be loaded into the classes of target, nor can it be used, and an error will be reported -- >


4. Mode 2: implement custom interface method through Mapper agent







Tags: xml Mybatis Java Maven

Posted on Sat, 20 Jun 2020 01:58:05 -0400 by spajetty