Getting started with Spring Boot 2.7.0 Mybatis (2)

What is Mybatis

MyBatis is an excellent persistence layer framework that supports custom SQL, stored procedures, and advanced mapping. Primitive types, interfaces, and Java POJOs (Plain Old Java Objects) can be configured and mapped through simple XML or annotations to records in the database.

​ Before the emergence of frameworks such as mybatis, most people connected to the database through jdbc, spliced ​​sql statements in java code and then executed them. The details are as follows:

1. Load the JDBC driver:

Class.forName("com.mysql.jdbc.Driver") ; 

2. Create a database connection:

Connection con = DriverManager.getConnection(url , username , password ) ; 

3. Execute prepared statements:

Statement stmt = con.createStatement() ;
//PreparedStatement pstmt = con.prepareStatement(sql) ;
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;

4. Traverse the result set for data analysis:

while(rs.next()){
    
    
   String name = rs.getString("name") ;
   String pass = rs.getString(1) ; 
}

The mybatis framework encapsulates and optimizes the above process, including: you can configure the data source to establish a connection pool; separate java and sql statements, sql statements can be written in xml configuration files, and the interface is defined in java; custom result sets and entity objects conversion. It greatly improves developers' coding efficiency, improves code readability, and saves database performance.

This tutorial uses the following version

spring boot 2.7.0

mybot 2.1.3

druid 1.2.1

mysql 5.6

Integrate

Create project

Create a new spring boot project. An empty project can be created via my previous tutorial.

Getting Started with Spring Boot

Edit pom file

After creating a new maven project in idea, you first need to introduce the following dependencies in the pom file.

Mainly includes: mybatis dependency, druid dependency, mysql dependency

 <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/>
    </parent>

    <dependencies>
        <!-- web 组件 -->
        <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>

        <!-- jdbc 组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- mybatis 组件 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <!-- druid 组件 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!-- mysql 组件 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>com.study.MainStarter</mainClass>
                    <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Don’t forget to reload the dependencies to prevent the jar package from being found! Click maven in turn, project name=》right click=》Reimport
Insert image description here

Directory Structure

Establish the package directory structure as shown below, the details are as follows:

Insert image description here

Create table statement

Execute the table creation statement we designed in the mysql5.6 database.

CREATE DATABASE /*!32312 IF NOT EXISTS*/studydb /*!40100 DEFAULT CHARACTER SET utf8 */;
USE studydb;
DROP TABLE IF EXISTS ser_company;
CREATE TABLE ser_company (
  company_id int(11) NOT NULL AUTO_INCREMENT COMMENT '公司id',
  company_name varchar(64) DEFAULT NULL COMMENT '公司名称',
  company_code varchar(4) DEFAULT NULL COMMENT '公司编号',
  company_msg text COMMENT '公司简介',
  company_crdt timestamp NULL DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (company_id)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;

Configure data source and mybatis

Add the following configuration to the application.properties configuration file :

#druid数据库连接池
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#数据库地址
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/studydb?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
#数据库账号
spring.datasource.username=root
#数据库密码
spring.datasource.password=root

#清除缓存
spring.thymeleaf.cache=false
#配置mapper映射路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置实体别名包路径
mybatis.type-aliases-package=com.study.model
#日志级别
logging.level.com.study.* = debug

Note that the database address, account, password, mapper mapping path, entity alias path, and log in the above configuration file need to be modified to your own database. Configuring the mapper mapping path will automatically scan the files in this path during the spring boot container. Configuring the entity alias package path eliminates the need to write the package name of the entity class when writing the class name in xml. The Alibaba druid database connection component is used here.

Entity class

Write an entity class under the com.study.model package, corresponding to the entities in the ser_company table. Let's take the company object as an example, which contains fields such as company name, company code, company information, and storage time. code show as below:

package com.study.model;

import org.apache.ibatis.type.Alias;

@Alias("SerCompanyVO")
public class SerCompanyVO {
    
    

    private int companyId;
    private String companyName;
    private String companyCode;
    private String companyMsg;
    private String companyCrdt;

    public int getCompanyId() {
    
    
        return companyId;
    }

    public void setCompanyId(int companyId) {
    
    
        this.companyId = companyId;
    }

    public String getCompanyName() {
    
    
        return companyName;
    }

    public void setCompanyName(String companyName) {
    
    
        this.companyName = companyName;
    }

    public String getCompanyCode() {
    
    
        return companyCode;
    }

    public void setCompanyCode(String companyCode) {
    
    
        this.companyCode = companyCode;
    }

    public String getCompanyMsg() {
    
    
        return companyMsg;
    }

    public void setCompanyMsg(String companyMsg) {
    
    
        this.companyMsg = companyMsg;
    }

    public String getCompanyCrdt() {
    
    
        return companyCrdt;
    }

    public void setCompanyCrdt(String companyCrdt) {
    
    
        this.companyCrdt = companyCrdt;
    }
}

dao

Edit the SerCompanyMapper class under the com.study.dao package to map the relevant interfaces in xml. Here you can choose an interface such as selectSerCompanyList for practice. Several interfaces are included in this tutorial. In addition to adding, modifying and deleting queries. This tutorial includes sample interfaces such as batch insertion, dynamic statement insertion and return of primary keys, dynamic statement modification, etc. code show as below:

package com.study.dao;

import com.study.model.SerCompanyVO;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface SerCompanyMapper {
    
    

    /**
     * 查询全部数据
     * @return
     */
    List<SerCompanyVO> selectSerCompanyList();

    /**
     * 根据id查询信息
     * @return
     */
    SerCompanyVO  selectSerCompanyById(Integer companyId);

    /**
     * 固定字段插入
     * @param serCompanyVO
     * @return
     */
    int insertSerCompanyVO(SerCompanyVO serCompanyVO);

    /**
     * 动态语句插入
     * @param serCompanyVO
     * @return
     */
    int insertSerCompanyDynamic(SerCompanyVO serCompanyVO);

    /**
     * 批量插入
     * @param list
     * @return
     */
    int insertCompanyBatch(List<SerCompanyVO> list);

    /**
     * 修改信息
     * @param serCompanyVO
     * @return
     */
    int updateCompany(SerCompanyVO serCompanyVO);

    /**
     * 动态语句修改
     * @param serCompanyVO
     * @return
     */
    int updateCompanyDynamic(SerCompanyVO serCompanyVO);

    /**
     * 根据id删除信息
     * @param companyId
     * @return
     */
    int deleteCompanyById(Integer companyId);
}

xml

In the mapper directory, create a new SerCompanyMapper.xml and write the following code:

namespace is the path of the dao layer interface class.

resultMap encapsulates the query result set into a SerCompanyVO object.

The foreach tag can traverse the list parameters.

useGeneratedKeys and keyProperty can return the primary key after insertion.

<?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.study.dao.SerCompanyMapper">

    <resultMap id="resultMap" type="SerCompanyVO">
        <id column="company_id" property="companyId" jdbcType="INTEGER" />
        <result column="company_name" property="companyName" jdbcType="VARCHAR" />
        <result column="company_code" property="companyCode" jdbcType="VARCHAR" />
        <result column="company_msg" property="companyMsg" jdbcType="VARCHAR" />
        <result column="company_crdt" property="companyCrdt" jdbcType="VARCHAR" />
    </resultMap>

    <!-- 新增数据 固定语句 -->
    <insert id="insertSerCompanyVO" useGeneratedKeys="true" keyProperty="companyId">
        insert into ser_company(
            company_name,
            company_code,
            company_msg,
            company_crdt
        ) values (
            #{companyName, jdbcType=VARCHAR},
            #{companyCode, jdbcType=VARCHAR},
            #{companyMsg, jdbcType=VARCHAR},
            #{companyCrdt, jdbcType=TIMESTAMP}
        )
    </insert>

    <!-- 新增数据 动态语句 -->
    <insert id="insertSerCompanyDynamic" useGeneratedKeys="true" keyProperty="companyId">
        insert into ser_company(
            <if test="null != companyName and ''!= companyName">
                company_name,
            </if>
            <if test="null != companyCode and ''!= companyCode">
                company_code,
            </if>
            <if test="null != companyMsg and ''!= companyMsg">
                company_msg,
            </if>
            <if test="null != companyCrdt and ''!= companyCrdt">
                company_crdt
            </if>
        ) values (
            <if test="null != companyName and ''!= companyName">
                #{companyName, jdbcType=VARCHAR},
            </if>
            <if test="null != companyCode and ''!= companyCode">
                #{companyCode, jdbcType=VARCHAR},
            </if>
            <if test="null != companyMsg and ''!= companyMsg">
                #{companyMsg, jdbcType=VARCHAR},
            </if>
            <if test="null != companyCrdt and ''!= companyCrdt">
                #{companyCrdt, jdbcType=TIMESTAMP}
            </if>
        )
    </insert>

    <!-- 新增数据 批量插入 -->
    <insert id="insertCompanyBatch">
        insert into ser_company(
            company_name,
            company_code,
            company_msg,
            company_crdt
        ) values
        <foreach collection="list" item="item" separator=",">
            (
                #{item.companyName, jdbcType=VARCHAR},
                #{item.companyCode, jdbcType=VARCHAR},
                #{item.companyMsg, jdbcType=VARCHAR},
                #{item.companyCrdt, jdbcType=TIMESTAMP}
            )
        </foreach>
    </insert>

    <update id="updateCompanyDynamic" >
        update ser_company set
        <if test="null != companyName and ''!= companyName">
            company_name = #{companyName, jdbcType=VARCHAR},
        </if>
        <if test="null != companyCode and ''!= companyCode">
            company_code = #{companyCode, jdbcType=VARCHAR},
        </if>
        <if test="null != companyMsg and ''!= companyMsg">
            company_msg = #{companyMsg, jdbcType=VARCHAR},
        </if>
        <if test="null != companyCrdt and ''!= companyCrdt">
            company_crdt =  #{companyCrdt, jdbcType=TIMESTAMP}
        </if>
        where company_id = #{companyId, jdbcType=INTEGER}
    </update>

    <update id="updateCompany">
        update ser_company set
        company_name = #{companyName, jdbcType=VARCHAR},
        company_code = #{companyCode, jdbcType=VARCHAR},
        company_msg = #{companyMsg, jdbcType=VARCHAR},
        company_crdt = #{companyCrdt, jdbcType=TIMESTAMP}
        where company_id = #{companyId, jdbcType=INTEGER}
    </update>

    <!-- 删除数据 -->
    <delete id="deleteCompanyById">
        delete from ser_company where company_id = #{companyId, jdbcType=INTEGER}
    </delete>

    <!-- 查询数据 -->
    <select id="selectSerCompanyList" resultMap="resultMap">
        select company_name, company_code, company_msg, company_crdt from ser_company
    </select>

    <!-- 详情查询 -->
    <select id="selectSerCompanyById" resultMap="resultMap" parameterType="java.lang.Integer">
        select company_id,company_name, company_code, company_msg, company_crdt from ser_company where company_id=#{companyId, jdbcType=INTEGER}
    </select>
</mapper>

service and implementation classes

Create a new SerCompanyService interface under the com.study.service package. The code is as follows:

package com.study.service;

import com.study.model.SerCompanyVO;

import java.util.List;

public interface SerCompanyService {
    
    

    List<SerCompanyVO> querySerCompanyList();

    int addCompany(SerCompanyVO serCompanyVO);

    int addCompanyDynamic(SerCompanyVO serCompanyVO);

    int addCompanyBatch(List<SerCompanyVO> list);

    SerCompanyVO querySerCompanyById(Integer companyId);

    int updateCompany(SerCompanyVO serCompanyVO);

    int updateCompanyDynamic(SerCompanyVO serCompanyVO);

    int deleteCompanyById(Integer companyId);
}

Create a new SerCompanyServiceImpl implementation class under the com.study.service.impl package. The code is as follows:

The SerCompanyMapper we just wrote is used here. Use this class to call statements in mybatis xml.

package com.study.service.impl;

import com.study.dao.SerCompanyMapper;
import com.study.model.SerCompanyVO;
import com.study.service.SerCompanyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SerCompanyServiceImpl implements SerCompanyService {
    
    

    private Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private SerCompanyMapper serCompanyMapper;

    @Override
    public List<SerCompanyVO> querySerCompanyList() {
    
    
        return serCompanyMapper.selectSerCompanyList();
    }

    @Override
    public int addCompany(SerCompanyVO serCompanyVO) {
    
    
        return serCompanyMapper.insertSerCompanyVO(serCompanyVO);
    }

    @Override
    public int addCompanyDynamic(SerCompanyVO serCompanyVO) {
    
    
        return serCompanyMapper.insertSerCompanyDynamic(serCompanyVO);
    }

    @Override
    public int addCompanyBatch(List<SerCompanyVO> list) {
    
    
        return serCompanyMapper.insertCompanyBatch(list);
    }

    @Override
    public SerCompanyVO querySerCompanyById(Integer companyId) {
    
    
        return serCompanyMapper.selectSerCompanyById(companyId);
    }

    @Override
    public int updateCompany(SerCompanyVO serCompanyVO) {
    
    
        return serCompanyMapper.updateCompany(serCompanyVO);
    }

    @Override
    public int updateCompanyDynamic(SerCompanyVO serCompanyVO) {
    
    
        return serCompanyMapper.updateCompanyDynamic(serCompanyVO);
    }

    @Override
    public int deleteCompanyById(Integer companyId) {
    
    
        return serCompanyMapper.deleteCompanyById(companyId);
    }
}

controller

Create the following class in com.study.controller:

package com.study.controller;

import com.study.model.SerCompanyVO;
import com.study.service.SerCompanyService;
import com.study.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
public class SerCompanyController {
    
    

    private Logger log = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private SerCompanyService serCompanyService;

    /**
     * 查询公司信息列表
     * http://localhost:8080/querySerCompanyList
     * @return
     */
    @RequestMapping(method= RequestMethod.GET, value = "querySerCompanyList")
    @ResponseBody
    public List<SerCompanyVO> querySerCompanyList(){
    
    
        if(log.isDebugEnabled()){
    
    
            log.debug("do querySerCompanyList begin.");
        }
        return serCompanyService.querySerCompanyList();
    }

    /**
     * 查询公司信息根据id
     * http://localhost:8080/querySerCompanyById?companyId=1
     * @return
     */
    @RequestMapping(method= RequestMethod.GET, value = "querySerCompanyById")
    @ResponseBody
    public SerCompanyVO querySerCompanyById(Integer companyId){
    
    
        return serCompanyService.querySerCompanyById(companyId);
    }

    /**
     * 新增公司固定字段
     * @param serCompanyVO
     * http://localhost:8080/addCompany?companyName=百度&companyCode=321&companyMsg=百度是一家上市公司
     * @return
     */
    @RequestMapping(method= RequestMethod.GET, value = "addCompany")
    @ResponseBody
    public Map<String, Object> addCompany(SerCompanyVO serCompanyVO){
    
    
        if(log.isDebugEnabled()){
    
    
            log.debug("companyName:{}", serCompanyVO.getCompanyName());
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        serCompanyVO.setCompanyCrdt(timestamp.toString());
        int num = serCompanyService.addCompany(serCompanyVO);
        Map<String ,Object> map =  ResultUtil.getRsMap(num);
        map.put("serCompanyVO", serCompanyVO);
        return map;
    }

    /**
     * 新增公司动态字段
     * http://localhost:8080/addCompanyDynamic?companyName=字节跳动&companyCode=&companyMsg=
     * @param serCompanyVO
     * @return
     */
    @RequestMapping(method= RequestMethod.GET, value = "addCompanyDynamic")
    @ResponseBody
    public Map<String, Object> addCompanyDynamic(SerCompanyVO serCompanyVO){
    
    
        if (log.isDebugEnabled()){
    
    
            log.debug("companyName:{}", serCompanyVO.getCompanyName());
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        serCompanyVO.setCompanyCrdt(timestamp.toString());
        int num = serCompanyService.addCompanyDynamic(serCompanyVO);
        Map<String ,Object> map =  ResultUtil.getRsMap(num);
        map.put("serCompanyVO", serCompanyVO);
        return map;
    }

    /**
     * 批量新增公司
     * http://localhost:8080/addCompanyBatch
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "addCompanyBatch")
    @ResponseBody
    public Map<String, Object> addCompanyBatch(){
    
    
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String timeStr = timestamp.toString();
        SerCompanyVO serCompanyVO = new SerCompanyVO();
        serCompanyVO.setCompanyName("导入1");
        serCompanyVO.setCompanyCode("3301");
        serCompanyVO.setCompanyCrdt(timeStr);
        SerCompanyVO serCompanyVO1 = new SerCompanyVO();
        serCompanyVO1.setCompanyName("导入2");
        serCompanyVO1.setCompanyCode("3302");
        serCompanyVO1.setCompanyCrdt(timeStr);
        List<SerCompanyVO> list = new ArrayList<>();
        list.add(serCompanyVO);
        list.add(serCompanyVO1);
        int num = serCompanyService.addCompanyBatch(list);
        return ResultUtil.getRsMap(num);
    }

    /**
     * 修改公司信息 固定语句
     * http://localhost:8080/updateCompany?companyId=13&companyName=百度2&companyCode=333&companyMsg=百度2是一家上市公司
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "updateCompany")
    @ResponseBody
    public Map<String, Object> updateCompany(SerCompanyVO serCompanyVO){
    
    
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String timeStr = timestamp.toString();
        serCompanyVO.setCompanyCrdt(timeStr);
        int num = serCompanyService.updateCompany(serCompanyVO);
        return  ResultUtil.getRsMap(num);
    }

    /**
     * 修改公司信息 动态语句
     * http://localhost:8080/updateCompanyDynamic?companyId=13&companyName=百度3&companyCode=333
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "updateCompanyDynamic")
    @ResponseBody
    public Map<String, Object> updateCompanyDynamic(SerCompanyVO serCompanyVO){
    
    
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String timeStr = timestamp.toString();
        serCompanyVO.setCompanyCrdt(timeStr);
        int num = serCompanyService.updateCompanyDynamic(serCompanyVO);
        return  ResultUtil.getRsMap(num);
    }

    /**
     * 删除公司信息
     * http://localhost:8080/deleteCompanyById?companyId=15
     * @param companyId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "deleteCompanyById")
    @ResponseBody
    public Map<String, Object> deleteCompanyById(Integer companyId){
    
    
        int num = serCompanyService.deleteCompanyById(companyId);
        return  ResultUtil.getRsMap(num);
    }
}

Startup class

Write the MainStarter class in com.study for spring boot startup. The code is as follows:

package com.study;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainStarter {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(MainStarter.class, args);
    }

}

test

Right-click to run the MainStarter class. Observe the console output as follows and observe that the project starts normally:

Insert image description here

Open the browser, enter the following address for interface testing, and select an interface to query data:

http://localhost:8080/querySerCompanyList

The results are as follows

Insert image description here

Other interface addresses can be found in the controller class and can be tested in sequence.

Okay, spring boot integration with mybatis is basically completed.

write at the end

Open source is a virtue, join the open source community as soon as possible and build a beautiful ecosystem together!

Guess you like

Origin blog.csdn.net/qq_36378416/article/details/125444521