javaee experiment: Spring Boot integrates Mybatis

My shoe

Introduction to MyBatis framework

Mybatis is formerly Apache's open source framework iBatis, which like Hibernate is a Java persistence layer framework
. The advantage of Mybatis is its flexibility. It can almost replace JDBC and provides interface programming. Currently, the data access layer DAO (Data Access Object) of Mybatis does not require an implementation class. It only requires an interface and XML (or annotations). Mybatis provides automatic mapping, dynamic SQL, cascading, caching, annotations, code and SQL separation and other features. It is easy to use and also optimizes SQL. Because it has less encapsulation, diversified mapping, supports stored procedures, and can perform SQL optimization, it has replaced Hibernate as the preferred persistence layer framework in the Java Internet. In the process of completing its functions, Mybatis mainly completes two things: 1) Encapsulates JDBC operations; 2) Use reflection to open up the relationship between Java classes and SQL statements. The Mybatis framework was built to solve the numerous coding problems that exist in traditional JDBC connection databases. Mybatis can use simple XML or annotations to configure and map native information, mapping interfaces and ordinary objects in Java into data records in the database< /span>









Mybatis framework execution flow chart

Insert image description here
SqlSession performs operations to query the database mapping file. Purpose:
1) Obtain the mapper, let the mapper find the corresponding SQL through the namespace and method name, send it to the database, and execute
Return the result after the line.
2) Directly execute SQL and return results through naming information.

mapper

MyBatis framework includes two types of XML files, one is the configuration file, namely mybatis-config.xml, and the other
is the mapping file, such as XXXMapper.xml, etc. The MyBatis configuration file mybatis-config.xml contains the
node, which is the MyBatis mapper.

  1. MyBatis mappers are divided into three categories, as follows:
    (1) Pure XML mapper, which uses various methods of SqlSession to implement additions, deletions, modifications and queries. For example:
    Person p = session.selectOne(“cn.mybatis.mydemo.mapper.PersonMapper.selectPersonById”, 1);
    (2) XML mapper +Mixed types of interface mappers
    Define the interface mapper first, and then define the xml mapper. The namespace of the xml mapper should correspond to the interface mapper.
    class name.
    (3) Mixed form of annotation + interface mapper
    In this form, the sql configuration information in the original xml is written in the form of Java annotations. Interface mapper, using the
    method is the same as the above example.
  2. Mixed type of XML mapper + interface mapper
    The mapper is composed of Java interface and XML file (or annotation). Its function is:
     Define parameter types
     Describe buffer description
     SQL statement definition
     Mapping relationship between query results and POJO< /span>
    Example: First define a mapper interface, as shown below
public interface StudentMapper {
    
    
 public Student getStudent(Long id);
}

Note: The mapper is just an interface, not an implementation class. Beginners may have a big question:
Isn’t the interface inoperable? It is true that the interface cannot be run directly, but MyBatis uses dynamic proxy technology internally to generate the implementation class of the interface to complete the related functions of the interface. Just understand that MyBatis will generate a proxy object for this interface, and the proxy object will handle the logic related to the mapper interface. Then, create the mapper in XML as follows:


<?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="cn.mybatis.mydemo.mapper.StudentMapper">
 <select id="getStudent" parameterType="long" resultType="student">
 SELECT id,name,address FROM Student WHERE id =#{id}
 </select>
</mapper>

With these two files, the definition of a mapper is completed. The introduction to the content of the XML file is as follows:
(1) The attribute namespace in the element corresponds to the fully qualified name of an interface, so
MyBatis context You can find the corresponding interface through it.
3
(2) The element indicates that this is a query statement, and the attribute id identifies this SQL, and the attribute
parameterType = "long" indicates that a long parameter is passed to SQL, and resultType="student"
indicates that a return value of Student type is returned. And student is the alias of the configuration file mybatis-config.xml configuration
, referring to com.mybatis.domain.Student. #{id} in this SQL represents the parameters passed in

Purpose

(1) Master the basic composition of the Mybatis framework
(2) Master how to integrate the Mybatis framework in Spring Boot
(3) Master the Mybatis framework Implement query and other operation methods

Experiment content

Spring Boot integrates the Mybatis framework to implement addition, deletion, modification and query operations of user information

experiment procedure

Database preparation

Prepare a table in mysql with username and non-Chinese content
The example is as follows

CREATE TABLE `t_user` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user_name` varchar(32) NOT NULL COMMENT '用户名称',
 `note` varchar(256) DEFAULT NULL COMMENT '备注',
 PRIMARY KEY (`id`)
)

Input data
Insert image description here

Project structure

Insert image description here

Code

IUserDao

import java.util.List;

/**
 * @author hongjun
 * @create 2020-10-28 17:27
 */
public interface IUserDao {
    
    

    /*
    * 查询所有用户信息
    * */
    List<User> findAll();
}

IUserDaoImpl

import com.example.mybatis1.domain.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * @author hongjun
 * @create 2020-11-01 9:49
 */
public class IUserDaoImpl  implements IUserDao{
    
    
    private SqlSessionFactory sqlSessionFactory;
    public IUserDaoImpl(SqlSessionFactory sqlSessionFactory){
    
    
        this.sqlSessionFactory=sqlSessionFactory;
    }
    @Override
    public List<User> findAll() {
    
    
       SqlSession sqlSession= sqlSessionFactory.openSession();
       List<User> userList=sqlSession.selectList("com.example.mybatis1.dao.IUserDao.findAll");
       sqlSession.close();
        return userList;
    }
}

User

import lombok.Data;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author hongjun
 * @create 2020-08-24 15:28
 *  id                   bigint not null,
 *     dept_id              bigint,
 *     username             varchar(20),
 *     password             varchar(50),
 *     realname             varchar(10),
 *     sex                  varchar(10),
 *     telephone            varchar(30),
 *     email                varchar(200),
 *     avatar               varchar(300),
 *     job_title            varchar(30),
 *     status               tinyint,
 *     sort                 int,
 *     del_flag             int comment '0 未删除 1 已删除',
 *     create_time          datetime,
 *     create_by            varchar(20),
 *     update_time          datetime,
 */
@Data
public class User {
    
    
   private Integer id;
   private Integer dept_id;
   private String username;
   private String password;
   private String realname;
   private String sex;
   private String telephone;
   private String email;
   private String avastar;
   private String jobTitle;
   private Integer status;
   private Integer sort;
   private Integer delFlag;
   private Date createTime;
   private Date updateTime;
   private String createBy;
}

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.example.mybatis1.dao.IUserDao">
    <select id="findAll" resultType="com.example.mybatis1.domain.User">
        select * from user
    </select>
</mapper>

SqlMapConfig.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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/stu?serverTimezone=Asia/Shanghai"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置映射文件的位置-->
    <mappers>
        <!--配置文件方式,每一个映射文件所在的地方-->
        <mapper resource="com/example/mybatis1/dao/IUserDao.xml"></mapper>
        <!--注解方式-->
       <!-- <mapper class="nuc.edu.mybatis.dao.IUserDao"></mapper>-->
    </mappers>

</configuration>

Experimental results

Insert image description here
As shown in the picture, it has been queried

Guess you like

Origin blog.csdn.net/m0_72471315/article/details/134856311