MyBatis learning summary (1): Introduction to MyBatis

One, MyBatis introduction

1. Three-tier architecture

       The three-tier architecture is not an actual technology, but a kind of "high cohesion, low coupling" idea, which divides each functional module into the presentation layer (UI), business logic layer (BLL) and data access layer ( DAL) three-tier architecture, each layer uses interfaces to access each other, and uses the entity class (Model) of the object model as the carrier of data transmission. The entity classes of different object models generally correspond to different tables in the database, and the attributes of the entity classes It is consistent with the field name of the database table. 

       The purpose of distinguishing the levels of the three-tier architecture is to "high cohesion, low coupling" to make the division of labor clearer, so as to focus more on the analysis, design and development of the core business logic of the application system, accelerate the progress of the project, and improve the development Efficiency is conducive to the update and maintenance of the project. as follows:

 The functions of each layer are as follows:

  • Presentation layer (UI): The interface presented to the user, which is responsible for receiving user information and displaying user information to the user, that is, what the user sees and gains when using a system.
  • Business Logic Layer (BLL): The operation for specific problems can also be said to be the operation of the data layer and the processing of data business logic.
  • Data Access Layer (DAL): This layer directly manipulates the database, aiming at adding, deleting, modifying, updating, and searching data.

       The traditional data access layer solutions are: JDBC, JdbcTemplate and DButils. JDBC is a specification, while JdbcTemplate and DBUtils are just tools. MyBatis is a framework for the data access layer. It is an encapsulation of jdbc, which makes the underlying operation of the database transparent. The following will give a detailed introduction to MyBatis.

2. Introduction to MyBatis

(1) Concept

       MyBatis is an excellent Java-based persistence layer framework, which encapsulates many details of JDBC operation, so that developers only need to pay attention to the SQL statement itself, rather than the complicated process of registering drivers and creating connections. It uses ORM idea to realize the encapsulation of result set. The ORM idea (Object Relational Mapping, object relational mapping) corresponds to the database table with the entity class and the attributes of the entity class, so that the database table can be operated by operating the entity class.

Mybatis can configure Sql statements in XML files to avoid hard coding Sql statements in Java classes. Compared with JDBC:

  • Through the parameter mapping method, Mybatis can flexibly configure the parameters in the configuration file in the SQL statement, avoiding the configuration of parameters in the Java class (JDBC)
  • Through the output mapping mechanism, Mybatis automatically maps the retrieval of the result set to the corresponding Java object, avoiding manual retrieval of the result set (JDBC)
  • Mybatis can manage database connections through Xml configuration files.

(2) Advantages:

  • Less code needs to be written compared to JDBC
  • Flexible to use, support dynamic SQL
  • Provides mapping tags, supports mapping between objects and database fields

(3) Disadvantages:

  • SQL statements depend on the database, and database portability is poor
  • SQL statement writing workload is heavy, especially when there are many tables and fields

Second, the entry program of MyBatis

       There are two ways to implement MyBatis: one is based on XML; the other is based on annotations. The introductory program here will be implemented in XML, and the annotation method will be completed in the process of subsequent article updates.

(1) Create the database table t_user and insert data

create table t_user(
    id int primary key auto_increment,
    username varchar(20),
    password varchar(20));
insert into t_user(username, password) values("张三", "zhangsan123");
insert into t_user(username, password) values("李四", "lisi123");
insert into t_user(username, password) values("tom", "123456");
insert into t_user(username, password) values("jerry", "jerry123456");

(2) Introduce the dependency of jar package in pom.xml.

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.25</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

  </dependencies>

(3) Create a log4j.properties file in the resources directory.

### 设置###
log4j.rootLogger = debug,stdout

### 输出信息到控制抬 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
pender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

(4) Create entity class User

public class User {
    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

(5) Create the interface class IUserDao.

public interface IUserDao {
    List<User> findAll();
}

(6) Create a hierarchical directory named com.day1.dao under the resource directory, and create the mapping file userMapper.xml in the package.

<?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">
<!--namespace:指定了唯一的命名空间-->
<mapper namespace="com.day1.dao.IUserDao">
    <!--
        id和接口中的方法名一致
        resultType返回值的参数类型
      -->
    <select id="findAll" resultType="com.day1.entity.User">
        select * from t_user;
    </select>
</mapper>

       In the above mapping file, the <mapper> element is the root element of the configuration file. It contains a namespace attribute whose value is usually set to "package name + SQL mapping file name", which specifies a unique namespace. The information in the sub-element <select> is the configuration used to query all data in the database.

(7) Create MyBatis configuration file SqlMapperConfig.xml.

<?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>
    <!--  配置环境  -->
    <environments default="mysql">
        <!--     配置MySQL的环境   -->
        <environment id="mysql">
            <!--     配置事务的类型       -->
            <transactionManager type="JDBC"></transactionManager>
            <!--     配置数据源(连接池)       -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///universaldb"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--  指定映射的配置文件位置:每一个都是独立的文件  -->
    <mappers>
        <mapper resource="com/day1/userMapper.xml"></mapper>
    </mappers>

</configuration>

(8) Create a test class

public class MyBatisTest {
    @Test
    public void testFindAll() throws IOException {
//1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IUserDao userDao = sqlSession.getMapper(IUserDao.class);
        //5、使用代理对象执行方案
        List<User> allUser = userDao.findAll();
        for(User user : allUser){
            System.out.println(user);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }
}

The execution results are as follows:

 A few notes:

(1) MyBatis workflow

Mybatis configures various statements (statement, preparedStatemnt, CallableStatement) to be executed through xml or annotation, and maps the SQL in the statement to the java object to generate the final executed sql statement, and finally the mybatis framework executes the sql and the result Map it into a java object and return it. It will be analyzed in detail later.

(2) MyBatis configuration file

  • SqlMapConfig.xml is a mybatis global configuration file, the name is not fixed, used to configure the operating environment, such as: data sources, transactions, etc.
  • The class name+mapper.xml is mainly used to configure SQL statements.

(3) Summary of errors·

 报错信息:A query was run and no Result Maps were found for the Mapped Statement

Reason: parameterType is the parameter passed in when sql is executed, and resuyltType is the data type returned by the query result. I mistakenly wrote resuyltType as parameterType.

Solution: Change the parameterType to resuyltType, because querying all the information of the data table in the database does not need to pass parameters.

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113624849