第四章 SpringBoot系列整合Mybatis做增删改查

系列文章目录

第一章 SpringBoot系列之从0搭建项目
第二章 SpringBoot系列返回json数据
第三章 SpringBoot系列GlobalException全局异常捕获
第四章 SpringBoot系列整合Mybatis做增删改查
第五章 SpringBoot系列配置JPA访问数据
第六章 SpringBoot系列使用JdbcTemplate操作数据
第七章 SpringBoot系列静态资源处理,访问磁盘文件


前言

本章内容在之前搭建的SpringBoot项目中整合Mybatis框架对数据库表做增删改查操作。


提示:以下是本篇文章正文内容,下面案例可供参考

一、Mybatis简介

MyBatis框架是一个开源的数据持久层框架。它的内部封装了通过JDBC访问数据库的操作,支持普通的SQL查询、存储过程和高级映射,几乎消除了所有的JDBC代码和参数的手工设置以及结果集的检索。主要是通过JAVA接口映射Mybatis的xml映射文件,可以说实现了半自动化操作流程,需要把SQL语句配置好映射JAVA接口就能实现对数据库的增删改查,很好的实现了代码解耦。

二、mysql建表

/*
Navicat MySQL Data Transfer

Source Server         : test
Source Server Version : 50718
Source Host           : localhost:3306
Source Database       : demo

Target Server Type    : MYSQL
Target Server Version : 50718
File Encoding         : 65001

Date: 2020-10-27 10:04:01
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `person`
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `age` int(3) NOT NULL,
  `sex` char(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES ('1', 'lc', '18', '男');

三、整合Mybatis步骤

1.在pom.xml文件中加入Mybatis依赖配置、mysql驱动包配置,并导入下载依赖jar包。

pom.xml文件配置:

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>1.3.0</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.47</version>
</dependency>

示例图:
在这里插入图片描述

2.application.properties数据库连接配置

########################################################
###datasource
########################################################
#数据库连接地址
spring.datasource.url = jdbc:mysql://localhost:3306/demo
#用户名
spring.datasource.username = root
#密码
spring.datasource.password = root
#驱动包
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
#指定连接池中最大的活跃连接数.
spring.datasource.max-active=20
#指定连接池最大的空闲连接数量.
spring.datasource.max-idle=8
#指定连接池最小的空闲连接数量.
spring.datasource.min-idle=0
#连接验证查询
spring.datasource.validationQuery=SELECT 1

########################################################
###Mybatis
########################################################
#映射文件
mybatis.mapper-locations = classpath:mybatis/*.xml

2.编写java操作数据库映射实体类,接口类,mybatis映射文件。

我这边直接用工具生策生成了代码:
①数据对象实体类PersonDO.java:

package com.example.demo.model;

import java.io.Serializable;

/**
 * person
 * @author 
 */
public class PersonDO implements Serializable {
    private Long id;

    private String name;

    private Integer age;

    private String sex;

    private static final long serialVersionUID = 1L;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

②Controller层方法

package com.example.demo.controller;

import com.example.demo.dto.JsonDataDTO;
import com.example.demo.model.PersonDO;
import com.example.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/")
public class DemoController {

    @Autowired
    private PersonService personService;
    
    @RequestMapping("/selectPersonInfo")
    public PersonDO selectPersonInfo(@RequestParam("id") Long id) {
        return personService.selectPersonInfo(id);
    }
}

③Service层方法

package com.example.demo.service;

import com.example.demo.mapper.PersonMapper;
import com.example.demo.model.PersonDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PersonService {

    @Autowired
    private PersonMapper personMapper;

    public PersonDO selectPersonInfo(Long id) {
        return personMapper.selectByPrimaryKey(id);
    }
}

④映射类抽象接口类MyBatisBaseMapper.java

package com.example.demo.mapper;

import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.annotations.Param;

/**
 * DAO公共基类,由MybatisGenerator自动生成请勿修改
 * @param <Model> The Model Class 这里是泛型不是Model类
 * @param <PK> The Primary Key Class 如果是无主键,则可以用Model来跳过,如果是多主键则是Key类
 */
public interface MyBatisBaseMapper<Model, PK extends Serializable> {
    int deleteByPrimaryKey(PK id);

    int insert(Model record);

    int insertSelective(Model record);

    Model selectByPrimaryKey(PK id);

    int updateByPrimaryKeySelective(Model record);

    int updateByPrimaryKey(Model record);
}

⑤映射类PersonMapper.java

package com.example.demo.mapper;

import com.example.demo.model.PersonDO;
import org.apache.ibatis.annotations.Mapper;

/**
 * PersonMapper继承基类
 */

public interface PersonMapper extends MyBatisBaseMapper<PersonDO, Long> {
}

⑥映射文件PersonMapper.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.demo.mapper.PersonMapper">
  <resultMap id="BaseResultMap" type="com.example.demo.model.PersonDO">
    <id column="id" jdbcType="BIGINT" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="sex" jdbcType="CHAR" property="sex" />
  </resultMap>
  <sql id="Base_Column_List">
    id, `name`, age, sex
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from person
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
    delete from person
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <insert id="insert" parameterType="com.example.demo.model.PersonDO">
    insert into person (id, `name`, age, 
      sex)
    values (#{id,jdbcType=BIGINT}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, 
      #{sex,jdbcType=CHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.example.demo.model.PersonDO">
    insert into person
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        `name`,
      </if>
      <if test="age != null">
        age,
      </if>
      <if test="sex != null">
        sex,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=BIGINT},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=CHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.model.PersonDO">
    update person
    <set>
      <if test="name != null">
        `name` = #{name,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=CHAR},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.demo.model.PersonDO">
    update person
    set `name` = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER},
      sex = #{sex,jdbcType=CHAR}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>

⑦启动类DemoApplication.java中加入@MapperScan(“com.example.demo.mapper”)注解,入参包路径,扫描com.example.demo.mapper包下面的类注册到spring容器做实例化,不然service类或其他类依赖注入mapper类对象会导致启动报错。

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement//开启事务管理
@MapperScan("com.example.demo.mapper")//扫描mapper类
public class DemoApplication {

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

}

四、demo运行效果

启动项目,浏览器访问:http://localhost:8080/selectPersonInfo?id=1
在这里插入图片描述


总结

本章内容主要是描述如何整合mybatis,从mybatis数据库建表到SpringBoot项目整合Mybatis从头到尾没有任何spring的xml配置,全程注解+配置做到加入Mybatis框架并成功查询数据,本次案例也基本贯穿了整个restful接口的开发流程,从Controller控制层到Service业务逻辑层再到Mapper数据操作层,看完本章内容基本也就能用SpringBoot做简单的增删改查了,本章就说到这里下章见。

原文地址:https://www.cnblogs.com/javakfz/p/13938209.html