IDEA 2020 MyBatis environment construction and entry case (using xml mode and annotation mode configuration)

Getting started with MyBatis

 

MyBatis environment construction

Use IDEA to build MyBatis environment

1. Create a Maven project and add dependencies

Create Maven project
Add dependency in pom.xml: (log4j can output the executed sql statement in the console for easy observation)

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13-beta-3</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2. Create an interface between entity classes and dao

Pay attention to the package name, create packages com.cjx.entity and com.cjx.dao under src/main/java

package com.cjx.entity;

import java.io.Serializable;
import java.util.Date;

/**
 * @author :
 * @date :Created in 2019/11/7 17:03
 * @description : user
 */
public class User implements Serializable {
    private int id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}
package com.cjx.dao;

import com.cjx.entity.User;

import java.util.List;

/**
 * @author :
 * @date :Created in 2019/11/7 17:07
 * @description : dao
 */
public interface IUserDao {

    /**
     * @author      :
     * @description :查询所有
     * @date        :Created in 2019/11/7
     */
    List<User> findAll();
}

3. Create the MyBatis main configuration file: SqlMapConfig.xml

Here you need to prepare a database in advance, here is named eesy_mybatis, the table is named user, and the design is as shown in the figure below:
Insert picture description here
just add some data to it.
Create the file SqlMapConfig.xml in resources

<?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">
<!-- MyBatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置MySQL环境 -->
        <environment id="mysql">
            <!-- 配置事务类型 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源/连接池 -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息  -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="1999"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 指定映射配置文件的位置 -->
    <mappers>
        <mapper resource="com/cjx/dao/IUserDao.xml"/>
    </mappers>
</configuration>

4. Create a mapping configuration file

Create the directory com.cjx.dao in resources, and then create the file IUserDao.xml

<?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.cjx.dao.IUserDao">
    <!-- 配置查询所有 -->
    <select id="findAll" resultType="com.cjx.entity.User">
        select * from user
    </select>
</mapper>

5. Create log4j configuration file

Create a log4j.properties file at the same level as SqlMapConfig

log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.R.File=../logs/service.log
#log4j.appender.R.layout=org.apache.log4j.PatternLayout
#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n

#log4j.logger.com.ibatis = debug
#log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug
#log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug
#log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug
#log4j.logger.java.sql.Connection = debug
log4j.logger.java.sql.Statement = debug
log4j.logger.java.sql.PreparedStatement = debug
log4j.logger.java.sql.ResultSet =debug

Precautions for setting up the environment

  1. The names of IUserDao.xml and IUserDao.java were created to be consistent with previous knowledge. The operation interface name and mapping file of the persistence layer are also called Mapper in MyBatis . So it may be called IUserMapper in other projects, and it must be understood at that time.
  2. Creating a directory in idea is not the same as a package. The package is created as com.cjx.dao , which is a three-level structure, and the directory com.cjx.dao, which is a level-1 directory, the name of the directory is "com.cjx.dao", and the directory must be created Use a slash , that is, com/cjx/dao , to create a three-level directory. In IDEA2019, the directory will be collapsed into the form of com.cjx.dao by default. If you want to create a service directory, it will still be in the resources directory. Create a com/cjx/service, you can create it normally.
    IDEA2019 directory structure

(This picture shows that in the case of com/cjx/dao, IDEA2019 will also collapse the directory into the form of com.cjx.dao by default)

  1. The location of the mapping configuration file of MyBatis must be the same as the package structure of the dao interface, the package is in com.cjx.dao, then the xml must also be in com/cjx/dao in the resources.
  2. The value of the namespace attribute of the mapper tag of the mapping configuration file must be the fully qualified class name of the dao interface.
  3. The operation configuration of the mapping configuration file (such as select), the value of the id attribute must be the method name of the dao interface, because the query operation has a return value, so you must specify a return result type, the attribute is resultType, and the value is the return value Class, here is user.

When we comply with points 3, 4, and 5, we no longer need to write the implementation class of dao during development, and the remaining functions will be implemented by MyBatis.
 

MyBatis entry case

Create a test function to implement database query

Create the package com.cjx.test in test/java, create the class MybatisTest, and create the Main function in the class. There are mainly the following steps:

  1. Read configuration file
  2. Create SqlSessionFactory factory
  3. Use the factory to produce a SqlSession object
  4. Use SqlSession to create proxy object of dao interface
  5. Use proxy objects to execute methods
  6. Release resources

code show as below:

package com.cjx.test;

import com.cjx.dao.IUserDao;
import com.cjx.entity.User;
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.InputStream;
import java.util.List;

/**
 * @author :
 * @date :Created in 2019/11/8 10:12
 * @description : 入门案例
 */
public class MybatisTest {
    /**
     * @author      :
     * @description :入门案例
     * @param       : [args]
     * @return      : void
     * @date        :Created in 2019/11/8
     */
    public static void main(String[] args) throws Exception {
        //1.读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3.使用工厂生产一个SqlSession对象
        SqlSession session = factory.openSession();
        //4.使用SqlSession创建dao接口的代理对象
        IUserDao userDao = session.getMapper(IUserDao.class);
        //5.使用代理对象执行方法
        List<User> users = userDao.findAll();
        for (User user :
                users) {
            System.out.println(user);
        }
        //6.释放资源
        session.close();
        in.close();
    }
}

Some problems that may occur after clicking Run

Release version 5 is not supported

This is because the default Java version of Maven is 1.5, and most people install the new version. The solution is as follows:

  1. Set the target bytecode version to 13 in File->Settings->Build,Excution, Deployment->Compiler->Java Compiler (mine is 13, others may be 1.8)Insert picture description here
  2. Add to the configuration at the same level as <dependencies> in pom.xml
    <properties>
       <java.version>13</java.version>
       <maven.compiler.source>13</maven.compiler.source>
       <maven.compiler.target>13</maven.compiler.target>
   </properties>
  1. Modify two Project SDKs in File->Project Structure->Project Settings->Project
    Insert picture description here
  2. Also modify a Language Level in Modules
    Insert picture description here

Time zone issues that may occur when accessing the database

Solution: Add the time zone parameter "?serverTimezone=UTC" after the database link, that is, modify this sentence in the SqlMapConfig.xml file

        <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis?serverTimezone=UTC"/>

Re-run this project using annotations

You can delete the mapping configuration file by using the annotation method and use the annotation instead to make the project more concise.

1. Add annotations to specify SQL statements in the dao interface

When creating the dao interface, add the annotation @Select("select * from user") to the findAll method to replace the mapping configuration file. code show as below:

package com.cjx.dao;

import com.cjx.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @author :
 * @date :Created in 2019/11/7 17:07
 * @description : dao
 */
public interface IUserDao {

    /**
     * @author      :
     * @description :查询所有
     * @date        :Created in 2019/11/7
     */
    @Select("select * from user")
    List<User> findAll();
}

2. Configure mapper in the main configuration file

In SqlMapConfig.xml, use the class attribute to specify the fully qualified class name of the dao interface when configuring the mapper. The code is as follows: (mainly the last few lines have changed), after the configuration is complete, you can add com.cjx.dao under resources. IUserDao.xml file is deleted, because annotations can completely replace the xml configuration file.

<?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">
<!-- MyBatis的主配置文件 -->
<configuration>
    <!-- 配置环境 -->
    <environments default="mysql">
        <!-- 配置MySQL环境 -->
        <environment id="mysql">
            <!-- 配置事务类型 -->
            <transactionManager type="JDBC"/>
            <!-- 配置数据源/连接池 -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息  -->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis?serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="1999"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 使用xml方式配置时这里指定映射配置文件的位置,但是本次使用注解配置,应该使用class属性指定被注解的dao全限定类名 -->
    <mappers>
        <mapper class="com.cjx.dao.IUserDao"/>
    </mappers>
</configuration>

After deleting IUserDao.xml and clicking Run again, it can still run successfully.

Guess you like

Origin blog.csdn.net/VABTC/article/details/110794228