cgb2107 - phase III - day02 mybatis

1.SpringBoot advanced usage

1.1 create a SpringBoot project using the general method
1.1.1 create maven project

1.1.2 edit pom.xml file
Note: for a new project, you only need to copy the configuration file other than the coordinates

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jt</groupId>
    <artifactId>springboot_demo2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--You only need to copy files other than coordinates-->
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.4.1</spring-boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.1</version>
                <configuration>
                    <mainClass>com.jt.SpringbootDemo1Application</mainClass>
                </configuration>
                <!--Exclude some specified configurations-->
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

1.2 environmental separation
1.2.1 requirements description
Scenario Description: if Xiao Li often goes back and forth between the company and the project base, the server port number often changes

Case:
1. Development: dev:8080 port
2. prod: 9000 port
Problem: due to the large number of configuration files, each modification will bring a lot of inconvenience, so you can use environment separation
1.2.2 editing yml configuration files
Pay attention to indentation when editing the configuration file
#Specifies the default configuration for the environment

spring:
  profiles:
    active: dev
---
#Define a name for the environment
server:
  port: 8080
spring:
  config:
    activate:
      on-profile: dev
# Environment segmentation is realized by -
---
server:
  port: 9000
spring:
  config:
    activate:
      on-profile: prod

1.3 hot deployment
1.3.1 requirements description
The configuration file / code needs to be frequently modified in the development stage. The requirements require that after the code is saved, the program will be compiled automatically and the tomcat service will be restarted. Individual idea versions may not take effect
1.3.2 add jar package

 <!--Support hot deployment and effective development phase-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

1.3.3 idea environment configuration (optional)
1. Configure automatic compilation

2. Make hot deployment effective
Shortcut keys: ctrl + alt + shift +/

Check automatic restart

1.4 database import
1.4.1 description of database link problems
Phenomenon: yesterday, the database can still be used normally. Today, it was turned on and found that the database can not be connected? What's the reason?
Cause: the service in windows may not be started
As shown in the figure: if the service item of the database is not started, it can be started

1.4.2 import database
After the database, import and refresh the database

1.5 lombok description
1.5.1 creating pojo objects

package com.jt.pojo;

import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Entity object requirements:
 *      1.Class names are generally associated with table names
 *      2.Attribute names are generally associated with fields
 *      3.pojo The property type in must be a reference type (wrapper type)
 *      4.Entity objects must have get/set methods
 *      5.General entity objects need to implement serialization interfaces (rules)
 *          Cause: data may be transmitted across platforms (servers) and must be serialized
 */
public class DemoUser implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;
}

1.5.2 lombok plug-in description
lombok can dynamically generate get/set/toString/hashcode/equals and other methods for pojo entity objects without manual editing
1.5.3 import jar package

<!--Introducing plug-ins lombok automatic set/get/Construction method plug-in  -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>



1.5.4 common notes

package com.jt.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * Entity object requirements:
 *      1.Class names are generally associated with table names
 *      2.Attribute names are generally associated with fields
 *      3.pojo The property type in must be a reference type (wrapper type)
 *      4.Entity objects must have get/set methods
 *      5.General entity objects need to implement serialization interfaces (rules)
 *          Cause: data may be transmitted across platforms (servers) and must be serialized
 */
@Data  //Dynamically generate get/set/toString/equals and other methods
@Accessors(chain = true) //Enable chained load override set method
@NoArgsConstructor  //Nonparametric structure
@AllArgsConstructor //Parametric structure
public class DemoUser implements Serializable {
    private Integer id;
    private String name;
    private Integer age;
    private String sex;

    //this runtime valid represents the current object
    /*public DemoUser setId(Integer id){
        this.id = id;
        return this;
    }*/

    //Method test
    public void add(){
        DemoUser user = new DemoUser();
        user.setId(100)
            .setName("aaaa")
            .setAge(18)
            .setSex("female");
    }

}



2.Mybatis
2.1 ORM idea
Object Relational Mapping (English: Object Relational Mapping, referred to as ORM, or O/RM, or O/R mapping) is a programming technology used to realize the conversion between data of different types of systems in object-oriented programming language. In effect, it actually creates a "virtual object database" that can be used in the programming language. Nowadays, there are many free and paid ORM products, and some programmers prefer to create their own ORM tools.
Summary: operate the database as an object
Derivative:

  1. Objects should be mapped to tables in the database one by one
  2. The attributes in the object should be mapped to the fields in the table one by one
  3. The mapping should be completed automatically by the program without human intervention

2.2 disadvantages of conventional JDBC

 //Use jdbc to complete the new functions
    private static void method2() throws Exception{
        //1. Register driver
        Class.forName("com.mysql.jdbc.Driver");
        //2. Get the connection to the database
        //ip port number and database name of data transfer protocol database
        String url = "jdbc:mysql://localhost:3306/cgb2107";
        Connection c = DriverManager.getConnection(url,"root","root");
        //3. Obtain the transmitter
        Statement s = c.createStatement();
        //4. Use the transmitter to execute the SQL of addition, deletion and modification
        //executeUpdate() is used to execute the SQL of addition, deletion and modification, and only returns the number of affected rows
        int rows = s.executeUpdate(
                "INSERT INTO emp(ename,job) VALUES('rose','Vice President')");
        //5. Release resources
        //r.close();// Result set
        s.close();//Transmitter
        c.close();//connect
    }

Disadvantages:

  1. Database links must be obtained regardless of execution. Link pool c3p0 druid HK link pool
  2. When operating sql statements, the steps are cumbersome and inconvenient for learning and memory
  3. The resource must be closed manually
    advantage:
    The fastest way to operate a database is JDBC. TCP protocol

2.3 Mybatis
2.3.1 introduction to mybatis
mybatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping. mybatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. (mybatis encapsulates JDBC internally)
MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.

Knowledge arrangement:
1. Persistence: when the computer is calculating, the data is in memory. If the power is off, the data will be cleared, so it is required to save the memory data to disk. Concept
2. Persistence layer: the layer code (Controller layer, Service layer, Dao/Mapper layer) at which the program interacts with the database through Dao/Mapper

Summary: Mybatis is an excellent persistence layer framework. Based on ORM design idea, it realizes the operation of database in the way of object
Understand: Mybatis's ORM is not complete. It only completes the result set mapping, but Sql needs to write by itself. Therefore, it is also called a semi-automatic ORM mapping framework

2.3.2 Mybatis features
Easy to learn: itself is small and simple. There is no third-party dependency. The simplest installation is as long as two jar files + several sql mapping files are configured. It is easy to learn and use. You can fully master its design idea and implementation through documents and source code.
Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. All requirements for operating the database can be met through sql statements.
Decouple sql and program code: by providing DAO layer, separate business logic and data access logic, so as to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
Provide mapping labels to support the mapping of orm fields between objects and databases
Provide object relationship mapping labels to support object relationship construction and maintenance
Provide xml tags to support writing dynamic sql.

2.4 introduction to mybatis
2.4.1 import jar package

  <!--mybatis Dependent package-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <!--jdbc Dependent package-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

2.4.2 editing POJO objects

package com.jt.pojo;

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

import java.io.Serializable;

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class DemoUser implements Serializable {

    private Integer id;
    private String name;
    private Integer age;
    private String sex;
}

2.4.3 edit mybatis-config.xml
Prepare the xml configuration file according to the official website description. Pay attention to the file path

<?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">
<!--Core profile-->
<configuration>

    <!--Environment configuration label default Only one environment can be written by default   -->
    <environments default="development">

        <!--Edit development environment  id Is the unique identifier of the environment  -->
        <environment id="development">
            <!--Transaction manager utilization jdbc Control transactions -->
            <transactionManager type="JDBC"/>
            <!--mybatis Integrate data sources by means of database link pool -->
            <dataSource type="POOLED">
                <!--High version database driver needs to be added cj-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/jt?serverTimezone=GMT%2B8&amp;useUnicode=true&amp;characterEncoding=utf8&amp;autoReconnect=true&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

    </environments>

    <!--Mybatis load Mapper Mapping file-->
    <mappers>
        <mapper resource="mybatis/mappers/UserMapper.xml"/>
    </mappers>
</configuration>

2.4.4 building persistent layer interface
Description: build mapper interface in com.jt.mapper

/**
 * explain:
 *      1.According to the idea of interface oriented development, a Mapper interface needs to be defined
 *      2.Interface methods can be written in the interface, who uses who to implement!!!
 */
public interface DemoUserMapper {

    //1. Query all table data
    public List<DemoUser> findAll();

}

2.4.5 build xml configuration file of mapper interface implementation class

<?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">
<!--xml The mapping file must be bound to the interface one-to-one
    namespace: Specify the interface name to bind. Cannot repeat.
 -->
<mapper namespace="com.jt.mapper.DemoUserMapper">

    <!--Implementing methods in interfaces
        id: It needs to be bound to the method in the interface. General copy and paste
        resultType: The package path of the object.
        rule: sql Don't add redundant statements;number  Oracle The database cannot be added;number
    -->
    <select id="findAll" resultType="com.jt.pojo.DemoUser">
        select id,name,age,sex from demo_user
    </select>

   <!-- <insert id=""></insert>
    <update id=""></update>
    <delete id=""></delete>-->

</mapper>

2.4.6 Mybatis association mapping file
Description: add the mappers tag in mybatis-config.xml file. Add the specified mapping file

	<!--Mybatis load Mapper Mapping file
        1.mapper The mapping files are located in order. Do not switch randomly
        2.adopt resource Load the specified xml Mapping file
    -->
    <mappers>
        <mapper resource="mybatis/mappers/demoUserMapper.xml"/>
    </mappers>

2.4.7 Mybatis realizes data query

 /**
     * Business description: an introductory case of implementing mybatis
     * Steps:
     *      1.Dynamically generate SqlSessionFactory
     *
     */
    @Test
    public void demo1() throws IOException {
        //Specify profile address
        String resource = "mybatis/mybatis-config.xml";
        //Loads the specified configuration file through the IO stream
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //Dynamically generate SqlSessionFactory
        SqlSessionFactory sqlSessionFactory =
                                new SqlSessionFactoryBuilder().build(inputStream);
        //Get SqlSession database link
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //Get Mapper interface
        DemoUserMapper demoUserMapper = sqlSession.getMapper(DemoUserMapper.class);
        //get data
        List<DemoUser> userList = demoUserMapper.findAll();
        System.out.println(userList);
        //Close link
        sqlSession.close();
    }

2.4.8 Mybatis calling process

2.5 Mybatis common error reports
2.5.1 BindingException exception description
Error reporting description 1:

org.apache.ibatis.binding.BindingException: Type interface com.jt.mapper.UserMapper is not known to the MapperRegistry.

Solution 1:
Check whether the namespace name is consistent with the interface

Error reporting Description 2:

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.jt.mapper.UserMapper.findAll

Solution 2:
Check whether the ID in the xml Mapping file is consistent with the interface method

Error reporting description 3:

The error may exist in mybatis/mappers/UserMapper2.xml

Solution 3:
Check whether the path of mybatis core file loading mapper mapping file is correct

Error reporting description 4:

Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML. The XML location is 'mybatis/mappers/demoUserMapper.xml'. Cause: org.apache.ibatis.builder.BuilderException: Error resolving class. Cause: org.apache.ibatis.type.TypeException: Could not resolve type alias 'DemoUser'. Cause: java.lang.ClassNotFoundException: Cannot find class: DemoUser

Solution 4:
The problem may be the type exception of resultType in the xml Mapping file

2.6 query data according to ID
2.6.1 edit business interface

public interface DemoUserMapper {

    //1. Query all table data
    public List<DemoUser> findAll();

    DemoUser findOne(int id);
}

2.6.2 editing xml Mapping Files

 <!--
         parameterType: Parameter type
         mybatis Passed in #{} get parameters
         resultType: Return value result object
    -->
    <select id="findOne" parameterType="int" resultType="com.jt.pojo.DemoUser">
        select * from demo_user where id = #{id}
    </select>

2.6.3 edit test API

/***
     *  Requirement: query the data of database record id=1 according to ID
     */
    @Test
    public void testFindOne() throws IOException {
        //Specify profile address
        String resource = "mybatis/mybatis-config.xml";
        //Loads the specified configuration file through the IO stream
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //Dynamically generate SqlSessionFactory
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //Get interface
        DemoUserMapper demoUserMapper = sqlSession.getMapper(DemoUserMapper.class);
        int id = 1;
        DemoUser demoUser = demoUserMapper.findOne(id);
        System.out.println(demoUser);
        //Close link
        sqlSession.close();
    }

Tags: Java Maven Mybatis Spring Boot yml

Posted on Thu, 23 Sep 2021 09:46:26 -0400 by lauxanh