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="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.wind</groupId>
    <artifactId>diy-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--MyBatis rely on-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!--MySQL Connection dependency-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <!--lombok Plug in dependency-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

    <!--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 config.properties 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-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

3, New database table

show databases;
use RUNOOB;
show tables;
select * from RUN_User;
desc RUN_User;
show create table RUN_User;
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',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Add time',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Update time',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB COMMENT='User table';

4, New Java entity class

@Data
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 "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

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

    <!--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"
                          value="jdbc:mysql://localhost:3306/RUNOOB?useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="admin0001112"/>
            </dataSource>
        </environment>
    </environments>

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

</configuration>

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 "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<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"/>
    </resultMap>

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

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

</mapper>

explain:

(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-->
    <mappers>
        <mapper resource="com/entity/mapper/UserMapper.xml"/>
    </mappers>

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 = sqlSessionFactoryBuilder.build(inputStream);
        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);
        sqlSession.commit();
        System.out.println(result);
    }

}

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 config.properties 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 -- >
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

 

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