springboot整合mybatis-plus完整案例
1.mybatis-plus,plus意思为插件,只在原来的基础上增强不做改变,只要进行简单的配置就可以对单表进行crud,还提供了强大的条件构造器wrapper以及代码生成器等。如下为springboot整合mybatis-plus的小案例,项目github地址:https://github.com/baisul/springbootmybatisplusDemo.git
2.要准备的sql语句用来建表
create table student(
id int(11) primary key auto_increment,
sname varchar(36) default null comment'姓名',
sno varchar(100) default null comment'学号',
sex tinyint(2) default null comment'性别,0男,1女',
hobby varchar(100) default null comment'爱好',
email varchar(100) default null comment'邮箱'
)
insert into student values(null,'小明','10001',0,'打篮球','xiaoming@163.com');
insert into student values(null,'小红','10002',1,'打羽毛球','xiaohong@163.com');
insert into student values(null,'小白','10003',0,'打篮球','xiaobai@163.com');
insert into student values(null,'小黑','10004',0,'打保龄球','xiaohei@163.com');
insert into student values(null,'小胖','10005',0,'打乒乓球','xiaopang@163.com');
insert into student values(null,'小新','10001',1,'打高尔夫球','xiaoxing@163.com');
create table teacher(
id int(11) primary key auto_increment,
tname varchar(36) default null comment'姓名',
tno varchar(100) default null comment'工号',
sex tinyint(2) default null comment'性别',
cource varchar(36) default null comment'教的课程'
)
insert into teacher values(null,'李小刚','t001',0,'体育');
insert into teacher values(null,'王春心','t002',1,'语文');
insert into teacher values(null,'李明','t003',0,'数学');
insert into teacher values(null,'小黑','t004',0,'物理');
3.新建一个工程,添加依赖
pomp.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--代码生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!--velocity模板引擎依赖-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
<!--freemarker模板引擎依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.用代码生成相关的实体类,以及mapper,service等,这里用的代码生成器有点问题,id居然没有生成在实体类里,本人手动添加的,关于mybatis-plus代码生成器的更多详细配置可以从这官方文档看更多详细配置
1)项目的结构
2)entity
package com.yl.demo.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author wfj
* @since 2020-11-12
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Student implements Serializable {
private static final long serialVersionUID=1L;
/**
* id
*/
@TableId(value="id",type= IdType.AUTO)
private Integer id;
/**
* 姓名
*/
private String sname;
/**
* 学号
*/
private String sno;
/**
* 性别,0男,1女
*/
private Integer sex;
/**
* 爱好
*/
private String hobby;
/**
* 邮箱
*/
private String email;
}
package com.yl.demo.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* <p>
*
* </p>
*
* @author wfj
* @since 2020-11-12
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Teacher implements Serializable {
private static final long serialVersionUID=1L;
/**
* id
*/
@TableId(value="id",type= IdType.AUTO)
private Integer id;
/**
* 姓名
*/
private String tname;
/**
* 工号
*/
private String tno;
/**
* 性别
*/
private Integer sex;
/**
* 教的课程
*/
private String cource;
}
3)service
package com.yl.demo.service;
import com.yl.demo.entity.Student;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author wfj
* @since 2020-11-12
*/
public interface IStudentService extends IService<Student> {
/**
* 获取学生列表
* @return
*/
List<Student> listStudent();
/**
* 根据学生ID查找学生
* @param id
* @return
*/
Student getStudentById(Integer id);
}
package com.yl.demo.service;
import com.yl.demo.entity.Teacher;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author wfj
* @since 2020-11-12
*/
public interface ITeacherService extends IService<Teacher> {
/**
* 新增一名老师
* @param teacher
* @return
*/
Integer addTeacher(Teacher teacher);
/**
* 获取所有女老师信息
* @return
*/
List<Teacher> getTeacherList();
}
4)service.impl
package com.yl.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yl.demo.entity.Student;
import com.yl.demo.mapper.StudentMapper;
import com.yl.demo.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author wfj
* @since 2020-11-12
*/
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {
@Resource
private StudentMapper studentMapper;
/**
* 这里调的是BaseMapper里的方法,List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
* @return
*/
@Override
public List<Student> listStudent() {
return this.studentMapper.selectList(new QueryWrapper<>());
}
/**
* 这里调的是ServiceImpl里面的方法,
* @param id
* @return
*/
@Override
public Student getStudentById(Integer id) {
return this.getById(id);
}
}
package com.yl.demo.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.yl.demo.entity.Teacher;
import com.yl.demo.mapper.TeacherMapper;
import com.yl.demo.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author wfj
* @since 2020-11-12
*/
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {
@Override
public Integer addTeacher(Teacher teacher) {
//调用ServiceImpl里的save方法,即可保存一个实体
return this.save(teacher) == true ? 1 : 0;
}
@Override
public List<Teacher> getTeacherList() {
//新建一个条件构造器,这个条件构造器就相当于在where后面拼接条件了
QueryWrapper<Teacher> wrapper = new QueryWrapper<>();
//设置查询条件字段sex=1的,eq等于,lt小于,gt大于,还有很多可以到官网查看
wrapper.eq("sex",1);
List<Teacher> list = this.list(wrapper);
return list;
}
}
5)util
package com.yl.demo.util;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.Data;
import java.io.Serializable;
/**
* 通用结果返回类
*/
@Data
public class Result implements Serializable {
public int code;
public String msg;
public Object data;
public static Result success() {
Result result = new Result();
result.setCode(200);
result.setMsg("操作成功");
return result;
}
public static Result success(int code,String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
public static Result success(int code,String msg,Object data) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(data);
return result;
}
public static Result success(Object data) {
Result result = new Result();
result.setCode(200);
result.setMsg("操作成功");
result.setData(data);
return result;
}
public static Result fail() {
Result result = new Result();
result.setCode(0);
result.setMsg("操作失败");
return result;
}
public static Result fail(int code,String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
public static Result fail(int code,String msg,Object data) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(data);
return result;
}
}
6)controller
package com.yl.demo.controller;
import com.yl.demo.entity.Student;
import com.yl.demo.service.IStudentService;
import com.yl.demo.util.Result;
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;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author wfj
* @since 2020-11-12
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private IStudentService studentService;
/**
* 获取学生列表
* @return
*/
@GetMapping("/listStudent")
public Result listStudent() {
List<Student> students = studentService.listStudent();
if (students != null) {
return Result.success(students);
} else {
return Result.fail();
}
}
/**
* 根据学生ID获取学生
* @param id
* @return
*/
@GetMapping("/getStudentById")
public Result getStudentById(@RequestParam Integer id) {
Student student = studentService.getStudentById(id);
if (student != null) {
return Result.success(student);
} else {
return Result.fail();
}
}
}
package com.yl.demo.controller;
import com.yl.demo.entity.Teacher;
import com.yl.demo.service.ITeacherService;
import com.yl.demo.util.Result;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author wfj
* @since 2020-11-12
*/
@RestController
@RequestMapping("/teacher")
public class TeacherController {
@Resource
private ITeacherService teacherService;
/**
* 添加老师
* @param teacher
* @return
*/
@PostMapping("/addTeacher")
public Result addTeacher(@RequestBody Teacher teacher) {
Integer result = teacherService.addTeacher(teacher);
if (result > 0) {
return Result.success();
} else {
return Result.fail();
}
}
@GetMapping("/listFemaleTeacher")
public Result listFemaleTeacher() {
List<Teacher> teacherList = teacherService.getTeacherList();
if (teacherList != null) {
return Result.success(teacherList);
} else {
return Result.fail();
}
}
}
7)mapper
package com.yl.demo.mapper;
import com.yl.demo.entity.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wfj
* @since 2020-11-12
*/
public interface StudentMapper extends BaseMapper<Student> {
}
package com.yl.demo.mapper;
import com.yl.demo.entity.Teacher;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wfj
* @since 2020-11-12
*/
public interface TeacherMapper extends BaseMapper<Teacher> {
}
8)mapper的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.yl.demo.mapper.StudentMapper">
</mapper>
<?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.yl.demo.mapper.TeacherMapper">
</mapper>
9 )application文件
spring.application.name=
#配置端口号以及访问路径
server.port=8080
server.servlet.context-path=/demo
#数据源
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatisplus配置
#开启驼峰命名法
mybatis-plus.configuration.map-underscore-to-camel-case=true
#扫描xml文件
mybatis-plus.mapper-locations=classpath:mapper/*.xml
10 )springboot主程序
5.用postman来进行接口测试
1)获取学生列表
2)根据学生id获取学生信息
3)添加老师
这里要设置请求头,contentype为application/json
4)获取所有女老师信息
6.最后,由上可以看出,单表的crud由此变得很简单,而且其提供的条件构造器也是很强大。
本文地址:https://blog.csdn.net/weixin_41359273/article/details/109647918
上一篇: SpringBoot日志
下一篇: Java学习第八天-----字符串
推荐阅读
-
SpringBoot2 整合Nacos组件,环境搭建和入门案例详解
-
SpringBoot 2.x 开发案例之 Shiro 整合 Redis
-
【SpringBoot】廿六、SpringBoot中整合MyBatis-Plus
-
SpringBoot系列(五)Mybatis整合完整详细版
-
微服务技术系列教程(46)-SpringBoot整合MongoDB(文章评论案例)
-
SpringBoot整合Mybatis完整详细版(快速整合)
-
详解SpringBoot开发案例之整合定时任务(Scheduled)
-
完整SpringBoot Cache整合redis缓存(二)
-
Springboot 整合 Dubbo/ZooKeeper 详解 SOA 案例
-
SpringBoot整合MyBatis实现增删改查案例完整版(附源代码)