SpringBoot笔记:SpringBoot集成MyBatis实战

文章目录

  • 1、前言
  • 2、代码实战
    • 2.1、pom.xml 配置
    • 2.2、yml 配置
    • 2.3、整体的代码层次结构
    • 2.4、Application 配置
    • 2.5、mysql 表结构
    • 2.6、Model
    • 2.7、Mapper
    • 2.8、Service
    • 2.9、Controller

1、前言

    因时间有限,简单说明一下 springboot 如何集成 mybatis的。详细的代码库地址:

https://gitee.com/leo825/springboot-learning-parents.git

推荐使用mybatis-plus:《SpringBoot笔记:SpringBoot集成MyBatisPlus实战》

2、代码实战

2.1、pom.xml 配置

本地开发使用 jdk8,mysql 版本 8.0.28


<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<groupId>org.examplegroupId>
		<artifactId>springboot-learning-parentsartifactId>
		<version>1.0-SNAPSHOTversion>
	parent>

	<modelVersion>4.0.0modelVersion>
	<groupId>springboot-demogroupId>
	<artifactId>springboot-mybatisartifactId>
	<version>1.0-SNAPSHOTversion>
	<name>springboot-mybatisname>
	<description>springboot 集成 mybatisdescription>
	<packaging>jarpackaging>

	<url>https://gitee.com/leo825/springboot-learning-parents.giturl>

	<properties>
		<start-class>com.demo.SpringbootMybatisApplicationstart-class>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
		<java.version>1.8java.version>
		<mybatis.version>1.3.2mybatis.version>
		<mysql.version>8.0.28mysql.version>
	properties>


	<dependencies>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starterartifactId>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-webartifactId>
		dependency>

		<dependency>
			<groupId>org.projectlombokgroupId>
			<artifactId>lombokartifactId>
			<optional>trueoptional>
		dependency>
		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-testartifactId>
			<scope>testscope>
		dependency>

		
		<dependency>
			<groupId>org.mybatis.spring.bootgroupId>
			<artifactId>mybatis-spring-boot-starterartifactId>
			<version>${mybatis.version}version>
		dependency>

		
		<dependency>
			<groupId>mysqlgroupId>
			<artifactId>mysql-connector-javaartifactId>
			<version>${mysql.version}version>
		dependency>
	dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.bootgroupId>
				<artifactId>spring-boot-maven-pluginartifactId>
			plugin>
		plugins>
	build>
project>

2.2、yml 配置

springboot 配置文件配置如下:

# springboot多环境配置
#端口,项目上下文
server:
  port: 8080
  servlet:
    context-path: /springboot-mybatis


spring:
  # mysql 数据库连接信息,本地使用 mysql 服务版本为:8.0.28
  datasource:
    username: root
    password: 6tojyh*A3eQ6
    url: jdbc:mysql://localhost:3306/local_test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
    driver-class-name: com.mysql.cj.jdbc.Driver

# mybatis 配置
mybatis:
  type-aliases-package: com.demo.model
  mapper-locations: classpath:mapper/*.xml

# 日志输出配置
logging:
  level:
    root: INFO
    org:
      springframework:
        security: WARN
        web: ERROR
    # 设置自己的 mapper 目录 输出sql日志
    com.demo.mapper: debug
  file:
    path: ./logs
    name: './logs/springboot-mybatis.log'
  pattern:
    file: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
    console: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'

2.3、整体的代码层次结构

SpringBoot笔记:SpringBoot集成MyBatis实战_第1张图片

2.4、Application 配置

使用 @MapperScan 注解,添加 Mapper

package com.demo;

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

@SpringBootApplication
@MapperScan(value = "com.demo.mapper")
public class SpringbootMybatisApplication {

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

2.5、mysql 表结构

create table t_user (
	id int (10) primary key auto_increment comment '用户主键',
	username varchar (100) not null comment '用户名称',
	pwd varchar(50) not null comment '密码',
	create_time datetime not null comment '创建时间',
	update_time datetime comment '修改时间'
) engine = innodb default charset = utf8 collate = utf8_bin comment '用户表';

2.6、Model

package com.demo.model;

import lombok.Data;

import java.io.Serializable;
import java.util.Date;


@Data
public class User implements Serializable {
    Integer id;
    String userName;
    String pwd;
    Date createTime;
    Date updateTime;
}

2.7、Mapper

package com.demo.mapper;

import com.demo.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    /**
     * 新增
     * @param user
     */
    void addUser(User user);

    /**
     * 删除用户
     * @param id
     */
    void deleteUserById(Integer id);

    /**
     * 更新用户
     * @param user
     * @return
     */
    void updateUser(User user);

    /**
     * 查询用户
     * @param ids
     * @return
     */
    List<User> getUsersById(List<Integer> ids);
}

mapper.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

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


    
    <resultMap type="com.demo.model.User" id="userMap">
        
        <id column="id" property="id">id>
        
        <result column="username" property="userName">result>
        
        <result column="pwd" property="pwd">result>
        <result column="create_time" property="createTime">result>
        <result column="update_time" property="updateTime">result>
    resultMap>


    
    <sql id="select">
		select * from t_user
	sql>
    
    <insert id="addUser" parameterType="com.demo.model.User">
        
        <selectKey keyColumn="id" keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        selectKey>
        insert into t_user
            (id,username,pwd,create_time,update_time)
        values(#{id},#{userName},#{pwd},#{createTime},#{updateTime})
    insert>

    
    <update id="updateUser" parameterType="com.demo.model.User">
        update t_user
        <set >
            <if test="userName != null">
                username = #{userName},
            if>
            <if test="pwd != null">
                pwd = #{pwd},
            if>
            update_time = #{updateTime}
        set>
        where id = #{id}
    update>

    
    <delete id="deleteUserById" parameterType="java.lang.Integer">
        delete from t_user where id = #{id}
    delete>

    
    <select id="getUsersById" parameterType="java.util.List" resultMap="userMap">
        <include refid="select">include>
        <where>
            
            <foreach collection="list" item="id" open="id in(" close=")" separator=",">
                #{id}
            foreach>
        where>
    select>
mapper>

2.8、Service

package com.demo.service;

import com.demo.model.User;

import java.util.List;

public interface UserService {
    /**
     * 新增
     * @param user
     */
    void addUser(User user);

    /**
     * 删除用户
     * @param id
     */
    void deleteUserById(Integer id);

    /**
     * 更新用户
     * @param user
     * @return
     */
    void updateUser(User user);

    /**
     * 查询用户
     * @param ids
     * @return
     */
    List<User> getUsersById(List<Integer> ids);
}

impl 实现类

package com.demo.service.impl;

import com.demo.mapper.UserMapper;
import com.demo.model.User;
import com.demo.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
    }

    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    @Override
    public List<User> getUsersById(List<Integer> ids) {
        return userMapper.getUsersById(ids);
    }
}

2.9、Controller

package com.demo.controller;

import com.demo.model.User;
import com.demo.service.UserService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.rmi.server.InactiveGroupException;

import javax.annotation.Resource;
import java.util.*;

@RestController
public class UserController {

    @Resource
    UserService userService;

    /**
     * 新增数据示例
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/add")
    private String getUserById(String username,String password){
        User user = new User();
        user.setUserName(username);
        user.setPwd(password);
        user.setCreateTime(new Date());
        userService.addUser(user);
        return "success";
    }

    /**
     * 根据id删除数据
     *
     * @param userId
     * @return
     */
    @RequestMapping("/delete")
    private String deleteUserById(String userId){
        Integer id = Integer.parseInt(userId);
        userService.deleteUserById(id);
        return "success";
    }


    /**
     * 修改用户数据的时候必须知道用户的id
     *
     * @param id
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/update")
    private String updateUser(String id, String username,String password){
        User user = new User();
        user.setId(Integer.parseInt(id));
        user.setUserName(username);
        user.setPwd(password);
        user.setUpdateTime(new Date());
        userService.updateUser(user);
        return "success";
    }


    /**
     * 根据id删除数据
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getUserList")
    private String getUsersById(String userId){
        String[] idsStr = userId.split(",");
        List<Integer> ids = new ArrayList<>();
        for(String str : idsStr){
            ids.add(Integer.parseInt(str));
        }
        List<User> users = userService.getUsersById(ids);
        return users.toString();
    }
}

通过 controller 可以进行新增、修改、查询、删除等操作了。

你可能感兴趣的:(SpringBoot,mybatis,spring,boot,java)