[New Trip-ssm] 3. Use of mybatis

3. Use of mybatis

[Objective]

I don't want to learn this ssm framework in order to understand the details of its implementation. Although many of the current enterprises use ssm frameworks, I don't need to find a job at this time. My purpose is clear. To build a web framework for my temporary use.

1. Preparations

1.1 Compilation environment: IDEA+mysql-server+Navicat Premium

Navicat Premium is a visual interface of mysql. My computer does not install it automatically according to the exe execution file of mysql. I just installed a database, a simple database, no visual interface and so on.

Blogs are available for specific installation methods

https://www.cnblogs.com/reyinever/p/8551977.html

http://www.runoob.com/mysql/mysql-install.html

I don't recommend installing the whole set because it's too big and mysql's own workbench isn't very useful, which I've been using before.

mysql-server+Navicat Premium was found to be very useful

1.2 Data Table Preparation

Insert data sql statement

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL COMMENT 'User Name',
  `birthday` datetime default NULL COMMENT 'Birthday',
  `sex` char(1) default NULL COMMENT 'Gender',
  `address` varchar(256) default NULL COMMENT 'address',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



insert  into `user`(`id`,`username`,`birthday`,`sex`,`address`) values (41,'King','2018-02-27 17:47:08','male','Beijing'),(42,'Erwang','2018-03-02 15:09:37','female','Beijing Jinyanlong'),(43,'Erwang','2018-03-04 11:34:34','female','Beijing Jinyanlong'),(45,'Wise Podcast','2018-03-04 12:04:06','male','Beijing Jinyanlong'),(46,'King','2018-03-07 17:37:26','male','Beijing'),(48,'Little Ma Baoli','2018-03-08 11:44:00','female','Beijing Amendment');

2. Use mybatis

Ignore the project on my left and click create new project directly on the right

Fill in the project name

Do not select a template

next

Enable automatic package import

2.1 Add pom.xml coordinates

<packaging>jar</packaging>
<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.5</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.11</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>2.10.0</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
    </dependency>
</dependencies>

2.2 Create User.java Entity Class

Property in User.java, corresponding to property in User table

Generate getter and setter methods

2.3 Create the IUserDao.java interface

This file is in the same level of directory as User.java, but in different packages.

2.4 Writing interface methods in IUserDao

2.5 Write the SqlConfigMap.xml configuration file

Here are some information about configuring the database connection. We chose the simplest configuration in this file. In fact, we can also separate the database connection information, but for convenience, we wrote it here directly.

This is all the code for this 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">

<configuration>
    <!--Configuration environment-->
    <environments default="mysql">
        <environment id="mysql">
            <!--Configure the type of transaction-->
            <transactionManager type="JDBC"></transactionManager>
            <!--Configure Data Source (Connection Pool)-->
            <dataSource type="POOLED">
                <!--Configure 4 basic information to connect to the database-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>


        </dataSource>
    </environment>
</environments>



</configuration>

2.6 Create an IUserDao.xml file

The IUserDao.xml file here is placed under the com.huiyu.dao folder, but you cannot create a three-level directory directly under the resources file. Create a folder three times at a time, such as creating com.huiyu.then a Dao folder, and finally an IUserDao.xml file.Otherwise, there will be problems here.

Write a query in this IUserDao.xml file

<?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.huiyu.dao.IUserDao">
    <!-- Configure Query All Operations -->
    <select id="findAll" resultType="com.huiyu.domain.User">   select * from user  </select>
    

</mapper>

This corresponds to the implementation of the interface written in the interface in IUserDao.java.

Once we've written this, we don't need to write any more implementation classes, which is equivalent to the findAll interface.

It is important to note that the id in select here is the interface method in our interface, which needs the same name.


This is equivalent to calling this query statement. Every time our system calls the interface in IUserDao.java, it will find the corresponding xml implementation here. In order to find this, we need to write out the package of our interface in namespace, so that the system knows that our xml corresponds to the interface method, select corresponds to the interface method, and use this termThe data queried by the sentence will be mapped to our result set.

So this resultType needs to define what class the return object needs to be encapsulated in.This is the User.java class we wrote earlier, which is why all the attributes in this class need to correspond to the attribute names in the database.Because the data queried by this select statement is data in the database, it needs to be encapsulated in the corresponding Java class to traverse printing in the Java language (so the explanation should be understood)

This would be equivalent to writing all the methods, and then in order for mybaitis to find this implementation, we need to add mapper in SqlConfigMap.xml

Almost all the methods are implemented, mostly mybatis automated, so we started writing test classes.

2.7 Writing test classes

Most of the details of the code for the test class are unknown.Just paste the code on:

package com.huiyu.test;

import com.huiyu.dao.IUserDao;
import com.huiyu.domain.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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Auther: huiyu
 * @Date: 2019/4/19
 * @Description: com.huiyu.test
 */
public class UserTest {

    private InputStream in;
    private SqlSession session;
    private IUserDao userDao;

    @Before
    public void init() throws IOException {
        //1. Read the configuration file
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2. Create a builder object for SqlSessionFactory
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        // 3. Use builder to create factory object SqlSessionFactory
        SqlSessionFactory factory = builder.build(in);
        //4. Use SqlSessionFactory to produce SqlSession objects
        session = factory.openSession();
        //5. Use SqlSession to create proxy objects for dao interfaces
        userDao = session.getMapper(IUserDao.class);
    }

    @After
    public void destory() throws IOException {

        session.commit();

        //7. Release Resources
        session.close();
        in.close();
    }


    /**
     * Find all introductory cases
     * @param
     */
    @Test
    public void findAllTest(){
        //6. Query all methods using proxy objects
        List<User> users = userDao.findAll();
        for(User user : users)
        {
            System.out.println(user);
        }
    }


}

Right-click on the finAllTest() method and select Run.You can then query the results we need.

Finally, take a look at the structure of the project:

Here log4j only needs to be copied in:

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

3. Summarize

What we do in sequence is:

  • Create Data Table
  • Create entity classes corresponding to tables, generate getter and setter methods, and generate toString methods
  • Create corresponding IUserDao.java interface class and write query interface methods
  • Create SqlConfigMap.xml and copy the configuration information into it
  • Create an IUserDao.xml file, write a select query statement, and map the result set to a java entity
  • Add here in SqlConfigMap.xml to map to our newly written IUserDao.xml file
  • Write test classes, run

Note: As long as you are familiar with this process, other additions, deletions, changes, and other operations follow this process, as for many of the code, such as in the test class:

Approaches to Individual Learning Framework

We don't need to know what these codes actually mean, just call the interface in dao in our test methods.

Once you are familiar with all the processes, you can go back and learn what these codes mean. For example, in IUserDao.xml, you can add where tags, aliases, and multi-table queries. But these complex queries are extended on this simple basis, and when we learn, we need to master the most basic framework.Hold.

Then we can derive some other complex operations from this framework, and complex operations are just adding a little more to this framework. By adding these things at this time, we can find related documents, such as the IUserDao.xml file, we can find documents, learn a lot of tags, and so on.

Therefore, learning needs to have a method, grasp the overall situation and look back at the local areas.

Keywords: log4j xml Java MySQL

Added by geowulf on Wed, 15 May 2019 18:22:03 +0300