有手就行的SpringBoot整合MyBatis

2024-03-06 07:38

本文主要是介绍有手就行的SpringBoot整合MyBatis,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

今天了解了通过SpringBoot整合MyBatis的框架 自己写一个博客复习一波

任务:创建两张表:

员工表(员工姓名, 员工的年龄, 员工性别, 部门id, id , 创建时间, 更新时间)部门表(id, 创建时间, 更新时间, 部门名称)执行每张表的CRUD自定义关联表查询 自定义业务场景

思路 : 首先通过mysql数据库创建两张表

CREATE DATABASE ead;
CREATE TABLE employees (id INT(10) PRIMARY KEY AUTO_INCREMENT,empName VARCHAR(50),empAge INT(10),empSex VARCHAR(10),depId INT(10),createBy DATE,updateBy DATE
);CREATE TABLE departments (id INT(10) PRIMARY KEY AUTO_INCREMENT,depName VARCHAR(50),createBy DATE,updateBy DATE
);INSERT INTO employees(id,empName,empAge,empSex,depId,createBy,updateBy) VALUES(1001,'李白',18,'男',1,NOW(),NULL);
SELECT * FROM employees;INSERT INTO departments(id,depName,createBy,updateBy) VALUES(1,'刺客',NOW(),NULL);
SELECT * FROM departments;

创建一个数据库名为:ead 分别创建两张表 雇员和部门 并为两张表各插入一条语句(执行该代码后,查询出的结果表如下)

雇员表

idempNameempAgecreateByempSexdepIdupdateBy
1001李白182020-08-181(null)

部门表

iddepNamecreateByupdateBy
1刺客2020-08-18(NULL)

表创建完成之后,打开idea创建一个SpringBoot开始整合MyBatis

在这里插入图片描述

进入idea选择Spring Initializr 点击下一步(Next)

在这里插入图片描述

输入自己的group和Artifact Java版本选择8或者以上 点击下一步

在这里插入图片描述

选择这两个依赖点击下一步,其他依赖可以直接进入后在pom文件中导入

在这里插入图片描述

直接点击finish 进入idea

在这里插入图片描述

进入后页面如下,我们需要整合mybatis框架,需要Mybatis和Mysql的jar包

我们在pom.xml文件的dependencys中添加以下两个依赖

<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>

依赖添加完成 我们在项目的src/main/java/com/pzy/ead下: 我们通过数据库表分别创建出每张表的 [实体类(entity),数据访问层(dao|mapper),业务逻辑层(Service),控制层(Controller)]

创建完成后表结构如下

在这里插入图片描述

在实体类表中根据数据库表字段创建字段信息

employees表实体类

package com.pzy.ead.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employees {private Integer id;private String empName;private Integer empAge;private String empSex;private Integer depId;private Date createBy;private Date updateBy;
}

Departments表实体类

package com.pzy.ead.entity;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.Date;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Departments {private Integer id;private String depName;private Date createBy;private Date updateBy;
}

创建实体类使用了lombok依赖

通过注解实现set,get方法以及无参构造和有参构造,减少了代码的构成

注:使用lombok时,需要先下载它的插件,否则可能无法使用

实体类创建完成后,打开resources文件 将application.propeties删除,我们使用application.yml文件进行springboot的配置 (配置mybatis和数据源)

在这里插入图片描述

分别在application.yml和application-dev.yml中添加如下代码

application.yml

spring:profiles:active: dev

application-dev.yml

server:port: 9000spring:datasource:username: pzypassword: 123url: jdbc:mysql://localhost:3306/ead?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTCdriver-class-name: com.mysql.cj.jdbc.Drivermybatis:mapper-locations: classpath:mapper/*Mapper.xmltype-aliases-package: com.pzy.ead.entity

创建完成两个yml文件后 我们根据application-dev的mybatis配置的mapper路径中创建两张数据库表的Mapper.xml文件

在这里插入图片描述

创建后在他们的命名空间中添加他们各自映射的Mapper的java文件路径,并分别写入一个查询语句测试一下

EmployeesMapper.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd">
<mapper namespace="com.pzy.ead.mapper.EmployeesMapper"><select id="selectAllEmployees" resultType="Employees">SELECT id,empName,empAge,empSex,depId,createBy,updateBy FROM employees;</select>
</mapper>  

DepartmentMapper.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd">
<mapper namespace="com.pzy.ead.mapper.DepartmentsMapper"><select id="selectAllDepartments" resultType="Departments">SELECT id,depName,createBy,updateBy FROM departments;</select>
</mapper>  

创建文件后我们在他们各自的Mapper的java文件中创建出这两个方法 并通过注解层层映射出来

DepartmentsMapper内代码

package com.pzy.ead.mapper;import com.pzy.ead.entity.Departments;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;import java.util.List;
@Repository
@Mapper
public interface DepartmentsMapper {List<Departments> selectAllDepartments();
}

EmployeesMapper内代码

package com.pzy.ead.mapper;import com.pzy.ead.entity.Employees;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;import java.util.List;
@Repository
@Mapper
public interface EmployeesMapper {List<Employees> selectAllEmployees();
}

在Mapper层中分别给两个接口方法名称与Mapper.xml文件处的一致

并添加注解使Service层能够自动创建此类

Service层

DepartmentsService

package com.pzy.ead.service;import com.pzy.ead.entity.Departments;
import com.pzy.ead.mapper.DepartmentsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
@Service
public class DepartmentsService {@AutowiredDepartmentsMapper departmentsMapper;public List<Departments> findAllDepartments(){return departmentsMapper.selectAllDepartments();}
}

EmployeesService

package com.pzy.ead.service;import com.pzy.ead.entity.Employees;
import com.pzy.ead.mapper.EmployeesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
@Service
public class EmployeesService {@AutowiredEmployeesMapper employeesMapper;public List<Employees> findAllEmployees(){return employeesMapper.selectAllEmployees();}
}

在Service中使用Autowired自动导入他们各自的Mapper对象,并在Service中添加注解Service以便于他们的控制器层的调用

控制层

DepartmentsController

package com.pzy.ead.controller;import com.pzy.ead.entity.Departments;
import com.pzy.ead.service.DepartmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class DepartmentsController {@Autowiredprivate DepartmentsService departmentsService;@RequestMapping("/findDep")public List<Departments> findAll(){return departmentsService.findAllDepartments();}
}

EmployeesController

package com.pzy.ead.controller;import com.pzy.ead.entity.Employees;
import com.pzy.ead.service.EmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class EmployeesController {@Autowiredprivate EmployeesService employeesService;@RequestMapping("/findEmp")public List<Employees> findAll(){return employeesService.findAllEmployees();}
}

最后在我们的项目启动处添加一个Mapper的扫描

@MapperScan(“com.pzy.ead.mapper”) 括号内是我们的Mapper包的路径 表示直接扫描我们的Mapper包内的所有接口 并与Mapper.xml文件进行绑定

package com.pzy.ead;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
@MapperScan("com.pzy.ead.mapper")
public class EadApplication {public static void main(String[] args) {SpringApplication.run(EadApplication.class, args);}}

运行项目 测试是否成功:

在这里插入图片描述
项目运行,通过我们设置的9000端口号与我们在控制器中设置的RequestMapping内的路径查询
在这里插入图片描述
在这里插入图片描述

测试成功 返回了我们需要的List集合格式

按照格式创建出两张表的CRUD

Mapper

DepartmentsMapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd">
<mapper namespace="com.pzy.ead.mapper.DepartmentsMapper"><select id="selectAllDepartments" resultType="Departments">SELECT id,depName,createBy,updateBy FROM departments;</select><select id="selectDepartments" resultType="Departments">SELECT id,depName,createBy,updateBy FROM departments WHERE id = #{id};</select><insert id="insertDepartments" parameterType="Departments">INSERT INTO departments(depName,createBy) VALUES(#{depName},now());</insert><delete id="deleteDepartments">DELETE FROM departments WHERE id = #{id}</delete><update id="updateDepartments" parameterType="Departments">UPDATE departments<set><if test="depName!=null and depName!=''">depName = #{depName},</if>updateBy = now()</set>WHERE id = #{id}</update>
</mapper>  

EmployeesMapper

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd">
<mapper namespace="com.pzy.ead.mapper.EmployeesMapper"><select id="selectAllEmployees" resultType="Employees">SELECT id,empName,empAge,empSex,depId,createBy,updateBy FROM employees;</select><select id="selectEmployees" resultType="Employees">SELECT id,empName,empAge,empSex,depId,createBy,updateBy FROM employees WHERE id = #{id};</select><insert id="insertEmployees" parameterType="Employees">INSERT INTO employees(empName,empAge,empSex,depId,createBy) VALUES(#{empName},#{empAge},#{empSex},#{depId},now());</insert><delete id="deleteEmployees">DELETE FROM employees WHERE id = #{id}</delete><update id="updateEmployees" parameterType="Employees">UPDATE employees<set><if test="empName!=null and empName!=''">empName = #{empName},</if><if test="empAge!=null">empAge = #{empAge},</if><if test="empSex!=null and empSex!=''">empSex = #{empSex},</if><if test="depId!=null">depId = #{depId},</if>updateBy = now()</set>where id = #{id}</update>
</mapper>  

Mapper Java代码

DepartmentsMapper

package com.pzy.ead.mapper;import com.pzy.ead.entity.Departments;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;import java.util.List;
@Repository
@Mapper
public interface DepartmentsMapper {List<Departments> selectAllDepartments();Departments selectDepartments(@Param("id") Integer id);Integer insertDepartments(Departments emp);Integer deleteDepartments(@Param("id") Integer id);Integer updateDepartments(Departments emp);
}

EmployeesMapper

package com.pzy.ead.mapper;import com.pzy.ead.entity.Employees;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;import java.util.List;
@Repository
@Mapper
public interface EmployeesMapper {List<Employees> selectAllEmployees();Employees selectEmployees(@Param("id") Integer id);Integer insertEmployees(Employees emp);Integer deleteEmployees(@Param("id") Integer id);Integer updateEmployees(Employees emp);
}

Service

DepartmentsService

package com.pzy.ead.service;import com.pzy.ead.entity.Departments;
import com.pzy.ead.mapper.DepartmentsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
@Service
public class DepartmentsService {@AutowiredDepartmentsMapper departmentsMapper;public List<Departments> findAllDepartments(){return departmentsMapper.selectAllDepartments();}public Departments findDepartments(Integer id){return departmentsMapper.selectDepartments(id);}public Integer addDepartments(Departments emp){return departmentsMapper.insertDepartments(emp);}public Integer removeDepartments(Integer id){return departmentsMapper.deleteDepartments(id);}public Integer modifyDepartments(Departments emp){return departmentsMapper.updateDepartments(emp);}
}

EmployeesService

package com.pzy.ead.service;import com.pzy.ead.entity.Employees;
import com.pzy.ead.mapper.EmployeesMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
@Service
public class EmployeesService {@AutowiredEmployeesMapper employeesMapper;public List<Employees> findAllEmployees(){return employeesMapper.selectAllEmployees();}public Employees findEmployees(Integer id){return employeesMapper.selectEmployees(id);}public Integer addEmployees(Employees emp){return employeesMapper.insertEmployees(emp);}public Integer removeEmployees(Integer id){return employeesMapper.deleteEmployees(id);}public Integer modifyEmployees(Employees emp){return employeesMapper.updateEmployees(emp);}}

控制层Controller

DepartmentsController

package com.pzy.ead.controller;import com.pzy.ead.entity.Departments;
import com.pzy.ead.service.DepartmentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class DepartmentsController {@Autowiredprivate DepartmentsService departmentsService;@RequestMapping("/findDep")public List<Departments> findAll(){return departmentsService.findAllDepartments();}@RequestMapping("/findDep/{id}")public Departments findEmp(@PathVariable Integer id){return departmentsService.findDepartments(id);}@RequestMapping("/addDep")public Integer createEmp(@RequestParam("depName") String depName){Departments dep = new Departments();dep.setDepName(depName);return departmentsService.addDepartments(dep);}@RequestMapping("/modifyDep")public Integer modifyEmp(@RequestParam(value = "depName",required = false) String depName,@RequestParam("id") Integer id){Departments dep = new Departments();dep.setId(id);if(depName!=null) {dep.setDepName(depName);}return departmentsService.modifyDepartments(dep);}@RequestMapping("/deleteDep/{id}")public Integer removeEmp(@PathVariable Integer id){return departmentsService.removeDepartments(id);}
}

EmployeesController

package com.pzy.ead.controller;import com.pzy.ead.entity.Employees;
import com.pzy.ead.service.EmployeesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class EmployeesController {@Autowiredprivate EmployeesService employeesService;@RequestMapping("/findEmp")public List<Employees> findAll(){return employeesService.findAllEmployees();}@RequestMapping("/findEmp/{id}")public Employees findEmp(@PathVariable Integer id){return employeesService.findEmployees(id);}@RequestMapping("/addEmp")public Integer createEmp(@RequestParam("depId") Integer depId,@RequestParam("empAge") Integer empAge,@RequestParam("empName") String empName,@RequestParam("empSex") String empSex){Employees emp = new Employees();emp.setDepId(depId);emp.setEmpAge(empAge);emp.setEmpName(empName);emp.setEmpSex(empSex);return employeesService.addEmployees(emp);}@RequestMapping("/modifyEmp/{id}")public Integer modifyEmp1(@RequestParam(value = "depId",required = false) Integer depId,@RequestParam(value = "empAge",required = false) Integer empAge,@RequestParam(value = "empName",required = false) String empName,@RequestParam(value = "empSex",required = false) String empSex,@PathVariable("id") Integer id){Employees emp = new Employees();emp.setId(id);emp.setDepId(depId);emp.setEmpAge(empAge);emp.setEmpName(empName);emp.setEmpSex(empSex);return employeesService.modifyEmployees(emp);}@RequestMapping("/deleteEmp/{id}")public Integer removeEmp(@PathVariable Integer id){return employeesService.removeEmployees(id);}
}

这篇关于有手就行的SpringBoot整合MyBatis的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/779309

相关文章

在Ubuntu上部署SpringBoot应用的操作步骤

《在Ubuntu上部署SpringBoot应用的操作步骤》随着云计算和容器化技术的普及,Linux服务器已成为部署Web应用程序的主流平台之一,Java作为一种跨平台的编程语言,具有广泛的应用场景,本... 目录一、部署准备二、安装 Java 环境1. 安装 JDK2. 验证 Java 安装三、安装 mys

Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单

《Springboot的ThreadPoolTaskScheduler线程池轻松搞定15分钟不操作自动取消订单》:本文主要介绍Springboot的ThreadPoolTaskScheduler线... 目录ThreadPoolTaskScheduler线程池实现15分钟不操作自动取消订单概要1,创建订单后

JAVA中整型数组、字符串数组、整型数和字符串 的创建与转换的方法

《JAVA中整型数组、字符串数组、整型数和字符串的创建与转换的方法》本文介绍了Java中字符串、字符数组和整型数组的创建方法,以及它们之间的转换方法,还详细讲解了字符串中的一些常用方法,如index... 目录一、字符串、字符数组和整型数组的创建1、字符串的创建方法1.1 通过引用字符数组来创建字符串1.2

SpringCloud集成AlloyDB的示例代码

《SpringCloud集成AlloyDB的示例代码》AlloyDB是GoogleCloud提供的一种高度可扩展、强性能的关系型数据库服务,它兼容PostgreSQL,并提供了更快的查询性能... 目录1.AlloyDBjavascript是什么?AlloyDB 的工作原理2.搭建测试环境3.代码工程1.

Java调用Python代码的几种方法小结

《Java调用Python代码的几种方法小结》Python语言有丰富的系统管理、数据处理、统计类软件包,因此从java应用中调用Python代码的需求很常见、实用,本文介绍几种方法从java调用Pyt... 目录引言Java core使用ProcessBuilder使用Java脚本引擎总结引言python

SpringBoot操作spark处理hdfs文件的操作方法

《SpringBoot操作spark处理hdfs文件的操作方法》本文介绍了如何使用SpringBoot操作Spark处理HDFS文件,包括导入依赖、配置Spark信息、编写Controller和Ser... 目录SpringBoot操作spark处理hdfs文件1、导入依赖2、配置spark信息3、cont

springboot整合 xxl-job及使用步骤

《springboot整合xxl-job及使用步骤》XXL-JOB是一个分布式任务调度平台,用于解决分布式系统中的任务调度和管理问题,文章详细介绍了XXL-JOB的架构,包括调度中心、执行器和Web... 目录一、xxl-job是什么二、使用步骤1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功

Java中的密码加密方式

《Java中的密码加密方式》文章介绍了Java中使用MD5算法对密码进行加密的方法,以及如何通过加盐和多重加密来提高密码的安全性,MD5是一种不可逆的哈希算法,适合用于存储密码,因为其输出的摘要长度固... 目录Java的密码加密方式密码加密一般的应用方式是总结Java的密码加密方式密码加密【这里采用的

Java中ArrayList的8种浅拷贝方式示例代码

《Java中ArrayList的8种浅拷贝方式示例代码》:本文主要介绍Java中ArrayList的8种浅拷贝方式的相关资料,讲解了Java中ArrayList的浅拷贝概念,并详细分享了八种实现浅... 目录引言什么是浅拷贝?ArrayList 浅拷贝的重要性方法一:使用构造函数方法二:使用 addAll(

解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题

《解决mybatis-plus-boot-starter与mybatis-spring-boot-starter的错误问题》本文主要讲述了在使用MyBatis和MyBatis-Plus时遇到的绑定异常... 目录myBATis-plus-boot-starpythonter与mybatis-spring-b