CGB2107-Day06-SpringBoot integrates Mybatis

CGB2107-Day06-SpringBoot integrates Mybatis

1. Supplementary knowledge of mybatis

1.1 special description of parameter value

        Knowledge points:
            1. Formal parameter/Arguments pass values,It has nothing to do with the name.
            2. resultMap When the hump mapping rule is turned on,Can be mapped automatically,Then use
               resultType that will do.
            3. If mybatis There is only one parameter passed,be mybatis Is to use subscript value.
                So the name is arbitrary #{xxxx}, but generally we need to pay attention to the development specifications
    <select id="findDeptById" resultType="Dept">
        select * from dept where dept_id = #{id}

1.2 proxy object description

1.2.1 common dynamic agents

  1. JDK dynamic agent
    1. It is required that the agent must implement (have) interfaces
    2.JDK agent is provided by jdk by default
  2. CGLIB dynamic proxy
    1. No matter whether the agent has an interface or not, you can create a proxy object for it The proxy object is a subclass of the target object
    2.cglib needs to import the jar package manually
    3.spring automatically adds cglib dependencies for the convenience of creating proxy objects

1.2.2 Mapper interface description

     * Case description: query department information according to id
     * Description of object creation:
     *      1.DeptMapper Is an interface Interface cannot instantiate object directly!!!
     *      2.The DeptMapper obtained is a proxy object dynamically generated by JDK for the interface
     *      3.The function of calling proxy object is consistent with that of interface
    public void testFindDeptById(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);
        int id = 100;
        Dept dept = deptMapper.findDeptById(id);

2. Integration of three frameworks

2.1 framework overview

2.1.1 Spring framework

Spring integrates complex frameworks for team development, making the program integrate from control to call Call in a unified way
Core: integrate the third-party framework

2.1.2 core mechanism of spring framework

  1. IOC:
    Inversion of control: the right to create objects is handed over to the Spring container, which manages the life cycle of objects
    DI: dependency injection
    When creating an object, Spring is responsible for assigning a value to the attribute if the object has a dependent attribute
	public class UserController {
		private UserService userService;
  1. AOP aspect oriented programming

2.1.2 SpringMVC

Note: the main function of this framework is to receive the user's request, complete the business processing, and finally return the response to the user

2.1.3 calling relationship between frameworks

2.2 realization of project integration

2.2.1 create project

  1. Create project

Select the springBoot version

2.2.2 edit POM XML file

Note: copy the POM in the previous project The XML file format is as follows

 <!--You only need to copy files other than coordinates-->
        <!--springBoot integration mvc-->

        <!--springBoot Integration test method-->

        <!--Support hot deployment and effective development phase-->

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

        <!--mybatis Package dependency-->

        <!--jdbc Package dependency-->



                <!--Exclude some specified configurations-->

2.3 editing core code

2.3.1 edit User's POJO

package com.jt.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;


@Accessors(chain = true)
public class User implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;

2.3.2 editing Mapper interface

package com.jt.mapper;

import com.jt.pojo.User;

import java.util.List;

public interface UserMapper {
    //Query demo_ All data in the user table
    List<User> findAll();

2.3.3 editing xml Mapping Files

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.jt.mapper.UserMapper">

    <select id="findAll" resultType="com.jt.pojo.User">
        select * from demo_user

2.3.4 edit Service interface and implementation class

1. Edit UserService interface

package com.jt.service;

import com.jt.pojo.User;

import java.util.List;

public interface UserService {

    //Query all data in user table
    List<User> findAll();

2. Edit ServiceImpl implementation class

package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
@Service    //Leave this class to the Spring container to manage
public class UserServiceImpl implements UserService{

    private UserMapper userMapper; //Proxy object JDK dynamic proxy

    public List<User> findAll() {
        //List<User> userList = userMapper.findAll();
        //return userList;
        return userMapper.findAll();

2.3.5 editing Controller

package com.jt.controller;

import com.jt.pojo.User;
import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController   //@When the Controller gives this class to the Spring container to manage the return value of + / / @ ResponseBody business, it converts the data into JSON
public class UserController {

    private UserService userService;

     * Requirement: query all user table data
     * Request type: get/post/put/delete
     * Path: / findUser
     * Parameter: None
     * Return value: List < user >
    public List<User> findUser(){

        return userService.findAll();


2.4 edit core configuration - application yml

2.4.1 data source configuration

Link writing:

  1. serverTimezone=GMT%2B8 specified time zone east zone 8
  2. useUnicode=true&characterEncoding=utf8
    Enable Unicode encoding and specify the character set utf-8
  3. autoReconnect=true whether to relink after disconnection
  4. &Allowmultiqueries = true allow batch operations

2.4.2 editing yml files

#Syntax: 1 Key: (space) value structure
  port: 8090

#Consolidate data sources
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://
    username: root
    password: root

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

2.5 Spring management Mapper interface

2.5.1 description of error reporting

2.5.2 @Mapper and @ MapperScan annotations

  1. @Mapper
  2. @MapperScan simplifies configuration information through package scanning

2.6 description of integrated error reporting

2.6.1 binding exception

  1. Check the namespace in the xml Mapping file
  2. Check the ID of Sql in the xml Mapping file

3. Check the import of xml Mapping file in YML file
Check whether the YML file is freeze frame and whether there is hierarchical indentation

4. Check @ MapperScan("com.jt.mapper")

2.6.2 abnormal database link

Description of error report: abnormal database link

Check database link address / username / password

3. Restful realizes parameter transfer

3.1 query data according to ID

3.1.1 request path

Get request type:


3.1.2 editing UserController

     * Business: query user data according to ID
     * Request type: get
     * URL:http://localhost:8090/findUserById?id=1
     * Parameter: id=1
     * Return value: User object
     * SpringMVC Business specification:
     *      1.When receiving parameters, they must be consistent with user parameters
    //@RequestMapping(value = "findUserById",method = RequestMethod.GET)
    @GetMapping("findUserById") //Only Get request types can be received
    public User findUserById(Integer id){

        return userService.findUserById(id);

3.1.3 edit UserService interface / implementation class

1. Edit business interface

  1. Editing concrete implementation

   package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
@Service    //Leave this class to the Spring container to manage
public class UserServiceImpl implements UserService{

    private UserMapper userMapper; //Proxy object JDK dynamic proxy
    public User findUserById(Integer id) {

        return userMapper.findUserById(id);

3.1.4 edit Mapper interface / mapping file

1. Edit Mapper interface

  1. Edit xml Mapping File
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"
<mapper namespace="com.jt.mapper.UserMapper">
    <select id="findUserById" resultType="User">
        select * from demo_user where id = #{id}

4 framework integration

  1. It is required to query user information according to name and age
    URL: http://localhost:8090/findUserByNA?name=xxx&age=xxx
  2. The name of the query ends with "xxx"
    URL: http://localhost:8090/findUserLike?name=xx
  3. Query data with id 1,3,5,6,7
    URL: http://localhost:8090/findUserByIds?id=1,3,5,6,7
  4. Query data according to non null elements in the object dynamic Sql query
    URL: http://localhost:8090/findUser?id=xx&name="xx"&age=xx&sex=xx
    URL: http://localhost:8090/findUser?age=xx&sex=xx
    URL: http://localhost:8090/findUser?sex=xx
  5. The update operation uses the structure of restFul to modify the data according to the Id and modify the name/age
    URL:http://localhost:8090/user/ Diao Chan / 18 / 227
    Resolution: URL:http://localhost:8090/user/{name}/{age}/{id}

5 spring MVC parameter passing

5.1 description of front-end controller

Front end controller: mainly responsible for receiving user requests and distributing back-end business processing

5.2 Servlet

5.2.1 what is a Servlet

Servlet (Server Applet) is the abbreviation of Java Servlet, which is called small service program or service connector. The server-side program written in Java is independent of platform and protocol. Its main function is to interactively browse and generate data and generate dynamic Web content.
Servlet in the narrow sense refers to an interface implemented by java language. Servlet in the broad sense refers to any class that implements the servlet interface. Generally, people understand servlet as the latter. The servlet runs in an application server that supports Java. In principle, servlets can respond to any type of request, but in most cases, servlets are only used to extend Web servers based on HTTP protocol.

Summary: Servlet is the mechanism (medium) for java background program to interact with users

5.2.2 cases of collusion

    public String findUserByIds(HttpServletRequest request){
        String id = request.getParameter("id");
        String[] idStr = id.split(",");
        Integer[] intArray = new Integer[idStr.length];
        for (int i=0;i<idStr.length;i++){
            intArray[i] = Integer.parseInt(idStr[i]);
        return "Parameter received successfully!!!";

     * Servlet Core rules of parameter transfer
     * http://localhost:8090/findServlet?name="Zhang San“
     * Question: where does the String name value come from????
     * Core: parameters are taken, not passed
     * Request process: a request object that returns a response
     * matters needing attention:
     *   1.Parameter names must be the same
     *   2.Disadvantages no matter what kind of data is, it is a String data type and needs to be converted manually
     * SpringMVC:
     *   The Servlet mechanism is encapsulated internally And it can realize automatic data processing according to the user's parameter type
     *   Type conversion
    public String findServlet(Integer age){

        return "get data:"+age;

    public String findServlet(HttpServletRequest request){
        String age = request.getParameter("age");
        Integer ageInt = Integer.parseInt(age);
        return "Get data: "+ age;

5.2.3 Preview

Follow the video to understand the installation principle of ElementUi scaffold client

Tags: Java

Posted by hawnted on Sun, 17 Apr 2022 14:48:54 +0930