转载

[Spring Boot] 结合 MyBatis 快速搭建

Hi 我是来自西部大嫖客 杰西

这篇文章主要是讲述如何使用 Spring Boot 结合 MyBatis 实现 CRUD。

搭建步骤

  1. 初始项目
  2. 初始数据库
  3. 导入依赖
  4. application.yml 添加上数据库的配置
  5. MybatisConfig 配置类
  6. 编写操作数据库的 model 层类
  7. 编写操作数据库的 mapper 文件及 repository 层类
  8. 编写操作数据库的 service 层的类
  9. 编写操作数据库的 controller 层的类

初始项目

初始化方法我一般用以下两种

  1. 通过 start.spring.io 自定义项目,然后下载/导入。
  2. 通过 IDEA 来新建 Spring Boot 项目。

初始数据库

创建一个数据库,库名为 demo001 ,然后执行以下 SQL

CREATE TABLE "sys_user" (
  "userId" bigint(11) NOT NULL AUTO_INCREMENT COMMENT '用户标识',
  "username" varchar(50) NOT NULL COMMENT '用户名',
  "password" varchar(100) DEFAULT NULL COMMENT '密码',
  "state" varchar(50) DEFAULT NULL COMMENT '状态:NORMAL正常  PROHIBIT禁用',
  PRIMARY KEY ("userId") USING BTREE,
  UNIQUE KEY "username" ("username") USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户表';

复制代码

导入依赖

<!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- lomkok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>
复制代码

由于 Mybatismapper 文件处于 resources 目录下,所以在 Mavan 打包的时候需要扫描 resource 目录。

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <!-- 打包时拷贝MyBatis的映射文件 -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
复制代码

application.yml 添加上数据库的配置

server:
  port: 8080
spring:
  datasource:
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.1.12:3521/demo001?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
    username: root
    password: root
复制代码

MybatisConfig 配置类

在项目目录下创建一个 config 文件夹,新建 MybatisConfig 文件。==记得 MapperScan 注解和 setTypeAliasesPackage 都替换成为自己相应的内容==。

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan("com.jc.demo001.repository")   // 扫描 mapper 接口
public class MybatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setTypeAliasesPackage("com.jc.**.model");    // 扫描实体类

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath*:mapper/*.xml"));    // 扫描映射文件

        return sessionFactory.getObject();
    }
}
复制代码

编写操作数据库的 model 层类

在项目目录下创建一个 model 文件夹,新建 SysUser.java

model/SysUser.java

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class SysUser {
    private Integer user_id;
    private String username;
    private String password;
    private String salt;
    private String state;
}

复制代码

编写操作数据库的 mapper 文件及 repository 层类

mapper 文件夹下创建一个 repository/SysUserMapper.java

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

public interface SysUserMapper {
    SysUser findUserById(@Param("id") Integer id);

    void deleteUserById(@Param("id") String id);

    void addUser(@Param("sysUser") SysUser sysUser);}

复制代码

并在 resources/SysUserMapper.xml,==记得替换里面的 namespace 和 resultType==。

<?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.jc.demo001.repository.SysUserMapper">

    <select id="findUserById" resultType="com.jc.demo001.model.SysUser">
        select * from sys_user where user_id = #{id}
    </select>

    <delete id="deleteUserById">
        DELETE FROM sys_user where user_id = #{id}
    </delete>

    <insert id="addUser" parameterType="com.jc.demo001.model.SysUser">
        insert info sys_user (username, password, salt, state) values (#{sysUser.username}, #{sysUser.password},  #{sysUser.salt},  #{sysUser.state})
    </insert>
</mapper>
复制代码

编写操作数据库的 service 层的类

我们先增加一个接口 service/SysUserService.java

public interface SysUserService {
    SysUser findUserById(String id);

    String deleteUserById(String id);

    String addUser(SysUser sysUser);
}

复制代码

然后添加一个实现类 service/impl/SysUserServiceImpl.java

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser findUserById(String id) {
        SysUser sysUser = sysUserMapper.findUserById(Integer.valueOf(id));
        return sysUser;
    }

    @Override
    public String deleteUserById(String id) {
        sysUserMapper.deleteUserById(id);
        return "success";
    }

    @Override
    public String addUser(SysUser sysUser) {
        sysUserMapper.addUser(sysUser);
        return "success";
    }
}
复制代码

编写操作数据库的 controller 层的类

添加个 controller

@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/info/{id}")
    public SysUser info(@PathVariable("id") String id) {
        SysUser sysUser = sysUserService.findUserById(id);
        return sysUser;
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") String id) {
        return sysUserService.deleteUserById(id);
    }


    @RequestMapping("/add/{id}")
    public String add(@RequestBody SysUser sysUser) {
        return sysUserService.addUser(sysUser);
    }

}
复制代码
原文  https://juejin.im/post/5e0c90d0e51d4541162c9471
正文到此结束
Loading...