Build the first MyBatis program

Project construction

  • IDEA creates an empty maven project
  • In the parent project POM Add dependencies to XML (mysql driver, mybatis dependency, and junit unit test)
  • Add a sub project to improve the package structure
<dependencies>
    <!-- mysql drive-->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>8.0.25</version>
       </dependency>
    <!-- mybatis drive-->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.5.7</version>
       </dependency>
       <!-- junit drive-->
       <dependency>
           <groupId>junit</groupId>
           <artifactId>junit</artifactId>
           <version>4.11</version>
           <scope>test</scope>
       </dependency>
   </dependencies>

Create a mybatis database

  • Create a new user table
  • Idea connect to database
CREATE TABLE `user`(
`id` INT(30) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
) ENGINE INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user`(`id`,`name`,`pwd`)
VALUES(1,'Zhang San','123456'),
(2,'He mengdan','666666'),
(3,'Wang Wu','42352356');

Write the core configuration file of mybatis

Create a new mybatis config. In the resources directory xml
Fill in the driver value column
Fill in the url address of the connection database in the url value column
Username and password write the database account and password respectively

<?xml version="1.0" encoding="UTF8" ?>
        <!DOCTYPE configuration
                PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
                "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--Core profile-->
<configuration>
<environments default="development">
    <environment id="development">
        <transactionManager type="JDBC"/>
        <dataSource type="POOLED">
            <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSl=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
            <property name="username" value="root"/>
            <property name="password" value="123456"/>
        </dataSource>
    </environment>
</environments>
</configuration>

Write the tool class of mybatis

Each MyBatis based application takes an instance of SqlSessionFactory as the core. An instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder. SqlSessionFactory builder can build a SqlSessionFactory instance from an XML Configuration file or a pre configured Configuration instance.

Building an instance of SqlSessionFactory from an XML file is very simple. It is recommended to use the resource file under the classpath for configuration. However, you can also use any input stream instance, such as an input stream constructed with a file path string or a file:// URL. MyBatis contains a tool class called Resources, which contains some practical methods to make it easier to load resource files from the classpath or other locations.

 try {
            //Step 1 of using mybatis: get sqlSessionFactory object
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

Get sqlSessionFactory object

Then get SqlSession from SqlSessionFactory

Complete mybatis tool class

 public static SqlSession getSqlSession(){
        return  sqlSessionFactory.openSession();
    }
public class MybatisUtils {

    private  static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            //Step 1 of using mybatis: get the sqlSessionFactory object
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
    Now that we have SqlSessionFactory, as the name suggests, we can get an instance of SqlSession from it.
    SqlSession Provides all the methods required to execute SQL commands in the database. You can use SqlSession
    Instance to directly execute the mapped SQL statement
    */
    public static SqlSession getSqlSession(){
        return  sqlSessionFactory.openSession();

    }

Write the entity class corresponding to the database

Interface class

public interface UserDao {
   List<User> getUserList();
}

Interface implementation

Create a usermapper XML file, sql code is written in this file. The function is to replace writing Java implementation classes and omit cumbersome JDBC code.

  • namespace binds a corresponding interface
  • id corresponds to the method of binding interface, and resultType corresponds to entity class
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

       <!--namespace Bind a corresponding interface-->
<mapper namespace="com.tt.Dao.UserDao">
     <!--id The method corresponding to the binding interface, resultType Corresponding entity class-->
    <select id="getUserList" resultType="com.tt.pojo.User">
        select * from mybatis.user
    </select>

</mapper>

test

Create a package with the same structure as src in the Test directory, write a Test class, and add the @ Test annotation

public class UserDaoTest {
    @Test
  public void Test(){
      // The first step is to obtain the sqlSession object
      SqlSession sqlSession = MybatisUtils.getSqlSession();
      //Execute sql
      UserDao userdao = sqlSession.getMapper(UserDao.class);
      List<User> userList = userdao.getUserList();

      //The second step is to traverse the output
      for (User user : userList) {
          System.out.println(user);
          System.out.println("-------------------------------");
      }
      //Close sqlSession
      sqlSession.close();;
  }
}

Running the test will encounter the following problems:

The reason is that the written xml implementing the interface needs to be registered in the core configuration file

<!--    every last Mapper.xml Must be registered in the core configuration file-->
    <mappers>
        <mapper resource="com/tt/dao/UserMapper.xml"/>
    </mappers>

The following problems will be encountered in the retest:

The reason is usermapper In the xmljava directory, resources cannot be exported. The solution is to configure resources in the parent project and child project to solve the resource export problem.

 <!--stay build Medium configuration resourceļ¼ŒTo prevent resource export problems-->
       <build>
           <resources>
               <resource>
                   <directory>src/main/resources</directory>
                   <includes>
                       <include>**/*.properties</include>
                       <include>**/*.xml</include>
                   </includes>
                   <filtering>true</filtering>
               </resource>
               <resource>
                   <directory>src/main/java</directory>
                   <includes>
                       <include>**/*.properties</include>
                       <include>**/*.xml</include>
                   </includes>
                   <filtering>true</filtering>
               </resource>
           </resources>
       </build>

success:

Problems encountered

When completing the above steps, the following error occurred:

The final solution is:
Change the encoding attribute value of xml from UTF-8 to UTF8, what a fuck!

Keywords: Mybatis

Added by raw100 on Sat, 22 Jan 2022 00:25:42 +0200