MyBatis3 detailed explanation of MyBatis basics

1. Introduction to Mybatis

1. What is Mybatis?

MyBatis was originally iBatis, an open source project of Apache. In 2010, the project was moved to Google Code by the Apache Software Foundation and renamed MyBatis. That is, iBatis was renamed MyBatis starting from version 3.0. And migrated to Github in November 2013, address: https://github.com/mybatis/mybatis-3. The word iBATIS comes from the combination of "internet" and "abatis" and is a persistence layer framework based on Java. The persistence layer framework provided by iBATIS includes SQL Maps and Data Access Objects (DAOs)

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and getting result sets. MyBatis can configure and map primitive types, interfaces and Java POJOs (Plain Old Java Objects) into records in the database through simple XML or annotations.

Describe Mybatis in one sentence: MyBatis is a persistence layer framework that can customize SQL, stored procedures and advanced mapping.

2. Some basic concepts

Mybatis is a Java-based persistence layer/ORM framework, so before we learn, let's first understand the following basic concepts.

①.What is “persistence”?

Persistence means saving data (such as objects in memory) to a storage device (such as a disk) that can be saved permanently. The main application of persistence is to store data in memory in a relational database. Of course, it can also be stored in disk files, XML data files, etc., but it is generally stored in relational databases such as MySQL, Oracle, etc.

②. What is "persistence layer"

Persistence Layer is a logical layer of a specific system that focuses on implementing data persistence application fields and associates data users with data entities. For example, the relationship between our pojo layer, Dao layer and Service layer.

③、What is “ORM”

ORM stands for Object-Relationl Mapping, which means object-relational mapping. It is used to implement conversion between object-oriented programming language types and relational database types. Simply put, ORM maps the objects in the program to the relational database by describing the metadata of the mapping between the object and the database. When we specifically operate the database, we will no longer need to deal with complex SQL statements. To deal with it, just operate it as you normally operate objects. But from the previous description, we know that our Mybatis needs to deal with SQL, so we think Mybatis is a semi-automated ORM framework.

Typical ORMs in Java include:

  • JPA: The full name of JPA is Java Persistence API, which is Java persistence API. It is a set of ORM-based specifications launched by Sun Company, which is composed of a series of interfaces and abstract classes. JPA describes the mapping relationship of object-relational tables through JDK 5.0 annotations or XML, and is Java's own framework.

  • Hibernate: Fully automatic ORM framework, powerful, complex, cumbersome, and expensive to learn. In addition to being an ORM framework, Hibernate is also a JPA implementation.

  • Mybatis: Semi-automatic ORM framework, powerful, simple, flexible, and low learning cost. Mybatis provides custom SQL so that developers can focus mainly on SQL.

The reason for persistence and ORM design is that persistence solves the problem of data storage, and ORM mainly solves the problem of object relationship mapping. In the current design of enterprise application systems, MVC is the main system architecture model (MVC is Model-View-Control). The Model in MVC contains complex business logic and data logic, as well as data access mechanisms (such as JDBC connection, SQL generation and Statement creation, and reading of ResultSet result sets, etc.). Separating these complex business logic and data logic to transform the tight coupling relationship of the system into a loose coupling relationship (i.e., decoupling) is an urgent task to reduce system coupling and is also a task to be done for persistence. The MVC pattern realizes the decoupling of the architectural separation of the presentation layer (i.e. View) and the data processing layer (i.e. Model). The persistence design realizes the decoupling of the separation of business logic and data logic within the data processing layer. As the most important and complex technology in persistence design, ORM is also a hot technology in the industry.

Generally, a persistent class corresponds to a table, each instance of the class corresponds to a record in the table, and each attribute of the class corresponds to each field of the table. It can be represented by a picture like the following:

Insert image description here
Next, we map table records in relational data into objects and display them in the form of objects, so that programmers can convert operations on the database into operations on objects.

Insert image description here
Therefore, the purpose of ORM is to facilitate developers to implement database operations using object-oriented thinking.

ORM's methodology is based on three core principles:

  • Simple: Model data in its most basic form.
  • Conveyability: The database structure is documented in a language that anyone can understand.
  • Accuracy: Create correctly standardized structures based on the data model.

3. Why use Mybatis

In the past, without an ORM framework, if you wanted to develop a Web application, you had to use traditional JDBC code to operate the database. In addition to providing SQL ourselves, we also had to operate Connection, Statment, ResultSet, etc. Not only that, in order to access data in different tables and fields, we need a lot of similar templated codes, and these codes are often repetitive, cumbersome and boring to write.

Let’s analyze the shortcomings of using traditional JDBC. Let’s first look at the following code:

public class SqlConnection {
    
    
 
    public static void main(String[] args) {
    
    
        //定义数据库连接
        Connection con = null;
        //定义数据库语句
        PreparedStatement ps = null;
        //定义返回结果集
        ResultSet rs= null;
 
        try {
    
    
            //加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //定义MySQL URL,因为这里有的长所以在这里定义了
            String url = "jdbc:mysql://localhost:3306/user?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8";
            //获取连接
            con = DriverManager.getConnection(url,"root","root");
            //定义SQL语句,?表示占位符
            String sql = "select * from t_user where username = ?";
            //获取编译处理的statement
            ps = con.prepareStatement(sql);
            //设置SQL参数
            ps.setString(1,"唐浩荣");
            //执行SQL语句查询,并且返回结果集
            rs = ps.executeQuery();
            //遍历结果集
            while (rs.next()){
    
    
                System.out.println(rs.getInt("id")+
                        "--"+rs.getString("username")+
                        "--"+rs.getInt("age"));
            }
 
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            //关闭数据库连接(三个写一起方便0.0)
            try {
    
    
                rs.close();
                ps.close();
                con.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Through the above piece of JDBC connection data code, we can see what are the disadvantages:

  • There is a hard coding problem when creating a Connection object. That is to say, the information for connecting to the database is directly hard-coded. If you need to connect to a different database, you need to change the configuration, which is inconvenient for later maintenance.
  • There is also a hard-coding problem when using PreparedStatement objects to execute SQL statements. The SQL statement is hard-coded into the Java code. If the SQL statement is modified, the Java code needs to be recompiled, which is not conducive to system maintenance.
  • Setting parameters to PreparedStatement, placeholder symbol positions and setting parameter values ​​are hard-coded in Java code, which is not conducive to system maintenance.
  • When traversing the result set data from the ResutSet, there is hard coding, and the fields of the obtained table are hard-coded. If the fields of the table are modified, the code also needs to be modified, which is not conducive to system maintenance.
  • The database connection will be created and closed every time a database connection is made. Frequent opening/closing of data connections will cause a waste of database resources and affect database performance.
  • The caching is very poor. If there is a large amount of data, the performance of this method is particularly low.

So through the above analysis, we know why we should use Mybatis. After using MyBatis, you only need to provide SQL statements. The rest, such as establishing connections, operating Statment, ResultSet, handling JDBC-related exceptions, etc., can be left to MyBatis. Our focus can then be focused on For SQL statements, focus on operations such as addition, deletion, modification, and query. And MyBatis supports the use of simple XML or annotations to configure and map native information, mapping interfaces and Java POJOs (Plain Old Java Objects, ordinary Java objects) into records in the database.

Let’s briefly talk about the advantages of Mybatis over JDBC:

  • Mybatis writes all the information for connecting to the database in the configuration file, so there is no hard-coding problem and it is convenient for later maintenance.
  • The SQL statements executed by Mybatis are configured through configuration files and do not need to be written in Java code.
  • Mybatis's connection pool management, cache management, etc. make connecting to the database and querying data more efficient.

4. Characteristics, advantages and disadvantages of Mybatis

Features:

  • MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping.
  • MyBatis encapsulates the calling details of the underlying JDBC API and can automatically convert the result set into a Java Bean object, greatly simplifying the repetitive work of Java database programming.
  • MyBatis avoids almost all JDBC code and manual setting of parameters and obtaining result sets.
  • MyBatis can use simple XML or annotations for configuration and primitive mapping, mapping interfaces and Java entities into records in the database.
  • MyBatis separates SQL statements from Java source programs and writes them in separate XML files, which brings great convenience to program maintenance.
  • MyBatis requires programmers to write SQL statements themselves. Programmers can flexibly control SQL statements based on the characteristics of the database itself. Therefore, it can achieve higher query efficiency than fully automatic ORM frameworks such as Hibernate and can complete complex queries.

advantage:

  • Easy to learn, Mybatis itself is small and simple, the entire source code is about 5MB. And it does not have any third-party dependencies. It is simple and practical and requires only a few Jar packages + a few SQL mapping files to configure. It also has official Chinese documents, so you can easily learn through the official documents.
  • Flexible to use, easy to get started and master. Compared with JDBC, less code needs to be written, reducing the amount of code by more than 50%.
    Provides XML tags to support writing dynamic SQL to meet different business needs.
  • SQL is written in XML, which facilitates unified management and optimization, and also decouples SQL from program code. Make the system design clearer, easier to maintain, and easier to unit test. The separation of SQL and code improves maintainability.
  • Provides mapping tags to support ORM field relationship mapping between objects and databases.
  • Provide object relationship mapping tags to support object relationship construction and maintenance.

shortcoming:

  • The workload of writing SQL statements is relatively large, especially when there are many tables and fields, which places certain requirements on developers' ability to write SQL.
  • SQL statements depend on the database, resulting in poor portability of the database and the database cannot be replaced at will.

Overall, MyBatis is a very excellent and flexible data persistence framework, suitable for Internet projects with changing needs, and it is also the current mainstream ORM framework.

5. The difference between Mybatis and Hibernate

Mybatis and Hibernate are both very popular persistence frameworks, so what are the differences between the Mybatis and Hibernate groups?

Let’s take a look below, because this question is likely to be asked in interviews.

①. Development:

  • Hibernate is a fully automatic ORM mapping tool. When you use Hibernate to query related objects or related collection objects, you can directly obtain them based on the object relational model, so it is fully automatic.
  • Mybatis is a semi-automatic ORM mapping tool. When Mybatis queries related objects or related collection objects, you need to manually write SQL to complete it. Therefore, it is called a semi-automatic ORM mapping tool. However, Mybatis can flexibly configure the SQL statements to be run through XML or annotations, map Java objects and SQL statements to generate the final executed SQL, and finally map the results of SQL execution to generate Java objects.

②. Bottom layer:

  • The bottom layer of Hibernate is the implementation of the JPA specification.
  • The bottom layer of Mybatis encapsulates the JDBC code.

③. SQL optimization:

  • Hibernate automatically generates SQL. Some statements are more cumbersome and will consume more performance.
  • Manually writing SQL in Mybatis can avoid unnecessary queries and improve system performance.

④. Learning costs:

  • The threshold for learning Hibernate is high, and the threshold for mastery is even higher. Moreover, how to design O/R mapping, how to weigh the performance and object model, and how to make good use of Hibernate require strong experience and ability.
  • Mybatis has a low learning threshold and is easy to learn. Programmers only need to focus on writing original ecological SQL. It can strictly control SQL execution performance and has high flexibility. It is very suitable for software development that does not have high requirements for relational data models, such as Internet software, enterprise operation software, etc., because the demand for this type of software changes frequently, once the demand changes, the results must be output quickly.

⑤.Object management

  • Hibernate is a complete object/relational mapping framework. It has extremely strong object/relational mapping capabilities. In development projects, you don’t need to pay too much attention to the underlying implementation, just manage the objects; and it has good database independence, so it is suitable for software with high requirements for relational models. (For example, customized software with fixed requirements) If you use Hibernate to develop, you can save a lot of code and improve efficiency.
  • Mybatis needs to manage the mapping relationship by itself; and Mybatis cannot be database independent. If you need to implement software that supports multiple databases, you need to customize multiple sets of SQL mapping files, which is a heavy workload.

⑥Log system:

  • The Hibernate log system is very sound and covers a wide range of issues, including: SQL records, relationship exceptions, optimization warnings, cache prompts, dirty data warnings, etc.
  • Mybatis has many weak functions except for the basic recording function.

⑦. Caching

Similarities:
In addition to using the system's default caching mechanism, the second-level caches of Hibernate and Mybatis can completely override the caching behavior by implementing your own cache or creating adapters for other third-party caching solutions.

difference:

  • Hibernate's second-level cache configuration is configured in detail in the configuration file generated by SessionFactory, and then the type of cache is configured in the specific table-object mapping. If dirty data occurs when using the second-level cache, the system will report an error and prompt.

  • MyBatis's secondary cache configuration is configured in detail in each specific table-object mapping, so that different caching mechanisms can be customized for different tables. And Mybatis can share the same cache configuration and instance in the namespace, through Cache-ref.

⑧. Summarize them in one sentence each:

  • Mybatis: small, convenient, efficient, simple, direct, semi-automatic. Metaphor: Mechanical tools are easy to use and can be used as soon as you bring them. But you still have to do the work yourself, but the tools are alive and it is up to me to decide how to use them.
  • Hibernate: Powerful, convenient, efficient, complex, indirect, and fully automated. Metaphor: An intelligent robot, but the cost of developing it (learning, proficiency) is very high. Work can be done away with it, but it is limited to what it can do.

In the end, no matter which persistence framework you use, they all have their own characteristics. In short, as long as a software architecture with good maintainability and scalability can be built according to the needs of users in a limited resource environment, it is a good architecture. Therefore, the best framework is only suitable.

6. Important components of MyBatis

Mybatis encapsulates the JDBC code. Let's analyze some important components that Mybatis gives us.

Insert image description here
Let's look from top to bottom. Some important components in MyBatis are as follows:

  • Mybatis configuration file: SqlMapConfig.xml is the global configuration file of Mybatis. It mainly configures data sources, transactions, loading mapping files, etc. Its name can be anything (it is best to know the meaning by name). Mapper.xml mainly configures Statement-related information, such as SQL statements.
  • SqlSessionFactoryBuilder: will generate SqlSessionFactory objects based on XML configuration or Java configuration. Use the builder mode (simply speaking, it is to build a large object step by step, such as building a big house, using the steps of buying bricks, laying bricks, and painting the walls) Construction, in which the big house is the big object, and the series of construction steps is the step-by-step construction).
  • SqlSessionFactory: used to generate SqlSession. SqlSession objects can be created through the SqlSessionFactory.openSession() method. Use the factory pattern (in simple terms, we obtain the object through a class, and this class creates the instance we need and returns it, instead of creating it ourselves through new).
  • SqlSession: Equivalent to the Connection object in JDBC. You can use the SqlSession instance to directly execute the mapped SQL statement or obtain the corresponding Mapper.
  • Executor: All Mapper statements in MyBatis are executed through Executor. (Mapper: It consists of XML files and Java interfaces. It executes the corresponding SQL statements according to the mapping information configured in the XML and returns the execution results.)
  • Mapper interface: The data operation interface is also commonly referred to as the DAO interface. It must correspond one-to-one with the methods in the Mapper configuration file, that is, it must be consistent with the add, delete, modify, check tag ID in Mapper.xml.
  • Mapper configuration: used to organize specific query business and map field relationships of the database, which can be implemented using XML format (Mapper.xml) or Java annotation format.
  • MappedStatement: Its function is to encapsulate Statement-related information, including SQL statements, input parameters, output results, etc.

7. Simple explanation of MyBatis execution process

  1. First, the global configuration file of Mybatis is loaded, and then the SQL mapping file or the related SQL content of the annotation is loaded.
  2. Create a session factory. MyBatis constructs a session factory (SqlSessionFactory) by reading the information in the configuration file.
  3. Create a session. According to the session factory, MyBatis can create a session object (SqlSession) through it. The session object is an interface that contains methods for adding, deleting, modifying, and querying database operations.
  4. Create an executor. Because the session object itself cannot directly operate the database, it uses an interface called the database executor (Executor) to help it perform operations.
  5. Encapsulate the SQL object. In this step, the executor encapsulates the SQL information to be processed into an object (MappedStatement), which includes the SQL statement, input parameter mapping information (Java simple type, HashMap or POJO) and output result mapping information ( Java simple types, HashMap or POJO).
  6. To operate the database, once you have the executor and SQL information encapsulation object, use them to access the database, and finally return the operation result to end the process.

2. Use of Mybatis

1. Create a database

Since Mybatis operates on the database, you must first create a database and a table. The database is named mybatis and the table is named t_user. This is for the MySQL database.

The SQL script is as follows:


DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  `sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, '奥利给', 18, '男', '上海');
INSERT INTO `t_user` VALUES (2, '蔡徐坤', 18, '男', '北京');
INSERT INTO `t_user` VALUES (3, '黄飞鸿', 42, '男', '大清');
INSERT INTO `t_user` VALUES (4, '十三姨', 18, '女', '大清');
INSERT INTO `t_user` VALUES (5, '梁宽', 42, '男', '大清');
INSERT INTO `t_user` VALUES (6, '马保国', 33, '男', '深圳');
INSERT INTO `t_user` VALUES (7, '纳兰元述', 42, '男', '大清');

2. Create a Maven project

Create a Maven project in Eclipse or IDEA.

Insert image description here
Then import the pom dependencies as follows:

<dependencies>
    <!-- Mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>
    <!-- 日志处理 -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!-- 单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>

3. Write User entity class

Create a User entity class. The getter, setter and toString methods are omitted here and need to be added by yourself.

/**
 * 用户实体类
 */
public class User {
    
    
    private Integer id;
    private String username;
    private Integer age;
    private String sex;
    private String address;

    //getter、setter、toString方法省略......
}

4. Create Mybatis global configuration file

Then in the resources directory, create the global configuration file mybatis-config.xml of Mybatis. It is the core configuration file of mybatis. The content of the configuration file is the data source, transaction management and the location of the specified mapping configuration file. code show as below:

<?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="development">
        <!-- id属性必须和上面的default一致 -->
        <environment id="development">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象源 -->
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/user?serverTimezone=GMT%2B8&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

A brief description of the configuration items in mybatis-config.xml:

  • environments: Configure the current environment. The default attribute has two options: development and work. The default is development development mode, and work is work mode.
  • environment: Configure the environment defined by each environment. You can configure multiple running environments, but each SqlSessionFactory instance can only select one running environment. Its id attribute also has two options: development and work, and must be consistent with the default attribute above. If two identical environments are configured, Mybatis will overwrite the previous one with the later one.
  • transactionManager: Configure the transaction manager type. There are two types of type attributes: JDBC and MANAGED. Only one can be configured at a time.
  • JDBC uses the JdbcTransaction object generated by the JdbcTransactionFactory factory to implement database submission, rollback and other operations in the JDBC manner. It relies on the connection obtained from the data source to manage the transaction scope.
  • MANAGED is implemented using the ManagedTransaction object generated by the ManagedTransactionFactory factory. Its submission and rollback do not require any operation. Instead, the transaction is handed over to the container for processing. The connection will be closed by default. If you do not want to close it by default, just set the closeConnection attribute in it. Just set it to false.
  • dataSource: Configure the data source type. The type attribute has three options: UNPOOLED, POOLED and JNDI:
    UNPOOLED (UnpooledDataSourceFactory): adopts a non-database pool management method. Each request will create a new connection and close it after use, so the performance is not very good. high. This method is suitable for simple applications with only a small number of concurrent users.
  • POOLED (PooledDataSourceFactory): Using the concept of connection pool to organize the database link object Connection, multiple connections can be created during initialization and obtained directly from the connection pool when used, avoiding the initialization and authentication time required to repeatedly create connections, thereby improving It improves efficiency, so this method is more suitable for applications with high performance requirements. This method is often used in development or testing environments.
  • JNDI (JndiDataSourceFactory): The implementation of data source JNDI is to be used in containers such as EJB or application servers. The container can configure the data source centrally or externally, and then place a reference to the JNDI context. Prefer this approach in production environments.
  • property: The property element in dataSource is database-related configuration information.

5. Write SQL mapping configuration file

We create a UserMapper.xml file under the directory resources—>mapper (the mapper directory is created by itself). All database operations in Mybatis will be based on the SQL statements configured in this mapping file. Any type of SQL statements can be configured in this configuration file. The framework will complete the mapping configuration of the input and output parameters of the SQL statement based on the parameter configuration in the configuration file.

Insert image description here
The file code looks like this:

<?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属性:表示命名空间,用来设定当前Mapper配置文件的唯一标识,将来在Java程序中通过namespace属性的值来定位到这个配置文件 -->
<!-- namespace属性值设置的方式:名字可以随便取,但是推荐以相对应的Mapper接口的全类名,例如com.thr.mapper.UserMapper -->
<mapper namespace="com.thr.mapper.UserMapper">
    <!-- 查询所有用户 -->
    <select id="selectAllUser" resultType="com.thr.entity.User">
        select * from t_user;
    </select>
    <!-- 通过Id查询一个用户 -->
    <select id="selectUserById" parameterType="int" resultType="com.thr.entity.User">
        select * from t_user where id = #{id};
    </select>
    <!-- 模糊查询,根据username字段查询用户-->
    <select id="selectUserByName" parameterType="int" resultType="com.thr.entity.User">
        select * from t_user where username like '%${value}%';
    </select>
    <!-- 添加用户-->
    <insert id="insertUser" parameterType="com.thr.entity.User">
        insert into t_user(username, age, sex, address)
        values (#{username}, #{age}, #{sex}, #{address});
    </insert>
    <!-- 根据Id更新用户 -->
    <update id="updateUser" parameterType="com.thr.entity.User">
        update t_user set username = #{username},
            age = #{age},sex = #{sex},address = #{address} where id = #{id}
    </update>
    <!-- 根据Id删除用户 -->
    <delete id="deleteUser" parameterType="int">
        delete from t_user where id = #{id}
    </delete>
</mapper>

6. Load mapping file

Add the UserMapper.xml file created above to the global configuration file mybatis-config.xml.

Insert image description here


<!--指定映射配置文件的位置,这个映射配置文件指的是每个业务独立的配置文件-->
<mappers>
    <mapper resource="mapper/UserMapper.xml"/>
</mappers>

7. Import log files

Import the log file, create the log4j.properties file in the resources directory, and import the following configuration (if the log reports an error, start Eclipse or IDEA as an administrator).

# 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

8. Write test code

Finally, create a MybatisTest test class, whose source code is as follows:

注意:使用JDBC的事务管理在进行增删改操作时,需要进行提交事务,也就是sqlSession.commit(),否则数据不会操作成功。

/**
 * Mybatis的测试
 */
public class MybatisTest {
    
    
    //定义 SqlSession
    SqlSession sqlSession = null;

    @Before
    public void getSqlSession() {
    
    
        //加载 mybatis 全局配置文件
        InputStream is = MybatisTest.class.getClassLoader().getResourceAsStream("mybatis-config.xml");
        //创建 SqlSessionFactory 对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //根据 sqlSessionFactory 产生 session
        sqlSession = sqlSessionFactory.openSession();
    }

    //查询所有用户数据
    @Test
    public void testSelectAllUser() {
    
    
        /**
         * 注意:这个字符串由 UserMapper.xml 文件中的两个部分构成(namespace + id)
         * <mapper namespace="com.thr.mapper.UserMapper">中 namespace 的值
         * <select id="selectAllUser" > 中的 id 值
         * 这样Mybatis才能找到需要的SQL
         */
        String statement = "com.thr.mapper.UserMapper.selectAllUser";
        List<User> listUser = sqlSession.selectList(statement);
        for (User user : listUser) {
    
    
            System.out.println(user);
        }
        sqlSession.close();
    }

    //根据Id查询一个用户数据
    @Test
    public void testSelectUserById() {
    
    
        String statement = "com.thr.mapper.UserMapper.selectUserById";
        User user = sqlSession.selectOne(statement, 1);
        System.out.println(user);
        sqlSession.close();
    }

    //模糊查询:根据 user 表的username字段
    @Test
    public void testSelectUserByName() {
    
    
        String statement = "com.thr.mapper.UserMapper.selectUserByName";
        List<User> listUser = sqlSession.selectList(statement, "三");
        for (User user : listUser) {
    
    
            System.out.println(user);
        }
        sqlSession.close();
    }

    //添加一个用户数据
    @Test
    public void testInsertUser() {
    
    
        String statement = "com.thr.mapper.UserMapper.insertUser";
        User user = new User();
        user.setUsername("张三");
        user.setAge(34);
        user.setSex("男");
        user.setAddress("中国深圳");
        int i = sqlSession.insert(statement, user);
        System.out.println( (i>0)? "添加成功!":"添加失败!");
        //提交插入的数据
        sqlSession.commit();
        sqlSession.close();
    }

    //根据Id修改用户数据
    @Test
    public void testUpdateUser(){
    
    
        //如果设置的 id不存在,那么数据库没有数据更改
        String statement = "com.thr.mapper.UserMapper.updateUser";
        User user = new User();
        user.setId(3);
        user.setUsername("王红");
        user.setAge(26);
        user.setSex("女");
        user.setAddress("中国上海");
        int i = sqlSession.update(statement, user);
        System.out.println( (i>0)? "修改成功!":"修改失败!");
        //提交数据
        sqlSession.commit();
        sqlSession.close();
    }

    //根据Id删除用户数据
    @Test
    public void testDeleteUser(){
    
    
        String statement = "com.thr.mapper.UserMapper.deleteUser";
        int i = sqlSession.delete(statement, 4);
        System.out.println( (i>0)? "删除成功!":"删除失败!");
        sqlSession.commit();
        sqlSession.close();
    }
}

Guess you like

Origin blog.csdn.net/GoodburghCottage/article/details/133355145