SSM integration / spring boot integration mybatis

1. Mybatis hump mapping

1.1 case demonstration

Problem Description: there are many scenarios where hump rules are used in work. However, if each attribute needs to be encapsulated manually, it is cumbersome. Therefore, the framework should provide the function of automatic mapping

1.2 description of hump rules

  1. Official website description:
  2. Setting settings
  <!--to configure settings information-->
        <!--Turn on hump mapping rules-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--type:  POJO Object path  alias: For current POJO Object alias-->
        <!--<typeAlias type="com.jt.pojo.User" alias="User"/>-->

        <!--Set alias package -->
        <package name="com.jt.pojo"/>
  1. Hump rule mapping description
 <!--Query user information and open hump mapping rules
                1.Applicable to single table query,At the same time, the attribute name should be the same as the field.
                2.If attributes and fields meet hump naming rules,After starting hump mapping,
                  have access to resultType
                1.Use if fields are inconsistent
                2.Used in multi table Association query.
                3.If hump mapping rule is enabled, Then the automatically mapped attributes can be omitted,It is best to identify the primary key
                4.If hump rule mapping is used,When mapping encapsulated objects is required(one-on-one/One to many),By default.Hump rule failure.
                  have access to: autoMapping="true" Hump mapping is required.
                5.One to one by default,One to many will not automatically complete hump rule mapping.
                  Configuration required autoMapping="true"To map automatically
    <select id="getAll" resultMap="getEmpMap">
        select e.emp_id,e.emp_name,
	    from emp e,dept d
	    where e.dept_id = d.dept_id
    <resultMap id="getEmpMap" type="Emp" autoMapping="true">
        <id column="emp_id" property="empId"/>
        <!--Automatic mapping of other attributes-->
        <!--Implement department mapping-->
        <association property="dept" javaType="Dept" autoMapping="true">
            <id column="dept_id" property="deptId"/>

2. Mybatis caching mechanism

2.1 cache concept

If a large number of the same requests query the database, the database needs to execute repeated sql for many times, so the concurrency pressure is high and the query efficiency is low. If the cache mechanism is introduced, the query efficiency of users can be greatly improved

2.2 Mybatis provides caching mechanism

There is a level 2 cache in Mybatis
The L1 cache sqlSession executes multiple queries within the same sqlSession. The cache is valid. The L1 cache is on by default
Level 2 cache SqlSessionFactory. Using the same factory, different sqlsessions created can realize data sharing (caching mechanism). Level 2 cache is also enabled by default

2.3 L1 cache test

Conclusion: if the same SqlSession is used to perform multiple database operations, the cache is effective. sql is executed only once

    public void testCache(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> list1 = empMapper.getAll();
        List<Emp> list2 = empMapper.getAll();
        List<Emp> list3 = empMapper.getAll();

2.4 L2 cache test

2.4.1 specify L2 cache

Syntax: specify cache tags in the respective xml mapping files

2.4.2 L2 cache test

Note: the L2 cache cannot take effect until sqlSession is closed

 //Test L2 cache
    public void testCache2(){
        SqlSession sqlSession1 = sqlSessionFactory.openSession();
        EmpMapper empMapper = sqlSession1.getMapper(EmpMapper.class);
        List<Emp> list1 = empMapper.getAll();
        sqlSession1.close(); //sqlSession must be closed after use. Otherwise, the L2 cache will not take effect
        //Create different sqlsessions using the same SqlSessionFactory
        SqlSession sqlSession2 = sqlSessionFactory.openSession();
        EmpMapper empMapper2 = sqlSession2.getMapper(EmpMapper.class);
        List<Emp> list2 = empMapper2.getAll();

2.4.3 precautions

If you need to use L1 / L2 cache, the POJO object must implement the serialization interface. Otherwise, the data cannot be cached
Schematic serialization rules:

3. Spring boot integrates Mybatis

3.1 create project

3.2 modify pom.xml file

Description: add dependency information to a new project



        <!--Introducing plug-ins lombok automatic set/get/Construction method plug-in  -->

        <!--mybatis Dependent package-->

        <!--jdbc Dependent package-->


3.3 code structure

3.4 spring boot integration with Mybatis

3.4.1 edit application.yml

#Configure port number
  port: 8090

#Manage data sources
    #Use of high version driver
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://
    #Set user name and password
    username: root
    password: root

#Spring boot integrates Mybatis
  #Specify alias package
  type-aliases-package: com.jt.pojo
  #Scan the mapping file under the specified path
  mapper-locations: classpath:/mybatis/mappers/*.xml
  #Turn on hump mapping
    map-underscore-to-camel-case: true

3.4.2 submit Mapper interface to container management

  1. Manage objects through @ Mapper annotations
@Mapper //The Mapper interface is managed by the Spring container
public interface UserMapper {

    List<User> findAll();
  1. Through package scanning, manage the mapper interface, edit the main startup class, and specify the package scanning path
//Scan the interface management object of mapper according to the specified package path
public class SpringbootSsmApplication {

    public static void main(String[] args) {, args);

3.4.3 Mybatis unit test case

class SpringbootSsmApplicationTests {

    @Autowired  //Inject the specified object
    private UserMapper userMapper; //IDEA compilation tips do not affect execution

     * Test spring boot integration with Mybatis
    public void testfindAll(){
        List<User> userList = userMapper.findAll();

3.5 description of Mapper interface object


  1. Give the interface to the spring container for management, and spring will dynamically select and create the proxy object according to the class type. Finally, give the proxy object to the spring container for management
  2. Use of proxy objects

3.5.1 introduction to agency mode JDK dynamic agent


  1. The agent must have an interface
  2. By default, if there is an interface, JDK dynamic proxy is used CGLIB dynamic agent


  1. A proxy object can be created for a delegate, whether or not it has an interface
  2. The proxy object is a subclass of the target object. Inheritance relationship


  1. If there is an interface in Spring, JDK proxy is used by default. If there is no interface, CGLIB proxy is used by default
  2. After spring 5, cglib is used when creating proxy objects from its own interface objects

3.6 SSM framework cases

3.6.1 business requirements

User access URL: http://localhost:8090/findAll
Return value: JSON string of List

3.6.2 framework diagram

3.6.3 level code implementation

3.6.4 editing UserController

@RestController  //@ResponseBody converts the list collection into json
public class UserController {

    private UserService userService;

     * URL: http://localhost:8090/findAll
     * Parameter: None
     * Return value: List < user >
    public List<User> findAll(){

        return userService.findAll();

3.6.5 editing UserService

public class UserServiceImpl implements UserService{

    private UserMapper userMapper;

    public List<User> findAll() {

        return userMapper.findAll();

3.6.5 editing UserService

public class UserServiceImpl implements UserService{

    private UserMapper userMapper;

    public List<User> findAll() {

        return userMapper.findAll();

3.6.6 editing UserMapper

mapper interface

public interface UserMapper {

    List<User> findAll();

mapper mapping file

<mapper namespace="com.jt.mapper.UserMapper">

    <!--Alias packages must be configured-->
    <select id="findAll" resultType="User">
        select * from demo_user

3.6.7 page effect display

4. Framework code case exercise

4.1 query data according to ID

4.1.1 requirements description

Query database by Id
URL: http://localhost:8090/findUserById?id=1
Return value: User object

4.1.2 editing UserController

     * Requirements: http://localhost:8090/findUserById?id=1
     * Parameter receiving: id=1
     * Return value: User object
    public User findUserById(Integer id){

        return userService.findUserById(id);

4.1.3 editing UserService

    public User findUserById(Integer id) {

        return userMapper.findUserById(id);

4.1.4 edit UserMapper

  //Only one of the annotation and mapping files can be selected
    @Select("select * from demo_user where id = #{id}")
    User findUserById(Integer id);

4.1.5 page effect display

4.2 query data according to age and sex

4.2.1 business requirements

URL: http://localhost:8090/findUserByAS
Return value: List collection encapsulation

4.2.2 editing UserController

     * URL Address: http://localhost:8090/findUserByAS?age=18&sex= female
     * Parameter: age = 18 sex = female
     * Return value: List < set >
     * Parameter receiving: if there are multiple parameters and the parameter name is consistent with the attribute name, object receiving can be used
        public List<User> findUserByAS(User user){

            return userService.findUserByAS(user);

4.2.3 editing UserService

    public List<User> findUserByAS(User user) {

        return userMapper.findUserByAS(user);

4.2.4 editing UserMapper

##4.3 RestFul parameter transfer

4.3.1 business requirements

Note: it is required to modify the data according to the id
restFul request path: http://localhost:8090/updateById/1/ Black bear essence / 3000 / male

4.3.2 editing UserController

     * URL:  http://localhost:8090/updateById/1/Black bear essence / 3000 / male
     * Parameters: 4
     * Return value: "modified successfully!!!"
     * restFul Structural parameter analysis {attribute name}
     * Parameter reception:
     *      1. A single parameter is received using @ PathVariable Integer id
     *      2. If multiple parameters are received, use the function automatically provided by the object mvc
    public String updateById(User user){

        return "User modified successfully";

4.3.2 editing UserService

 //After spring integrates mybatis, transactions are automatically committed
    public void updateById(User user) {


4.3.2 editing UserMapper

@Update("update demo_user set name=#{name},age=#{age},sex =#{sex} where id=#{id}")
    void updateById(User user);

Tags: Java Spring Boot Back-end SSM

Posted on Tue, 02 Nov 2021 08:28:59 -0400 by rednaxel