官方文档:https://baomidou.com/
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
注意
适用版本:mybatis-plus-generator 3.5.1 以下版本,3.5.1 及以上的请参考 代码生成器新
这个项目是一个多表查询并分页
smbms_user用户表
名称 | 类型 | 长度 | 描述 |
---|---|---|---|
id | bigint | 20 | 主键ID |
userCode | varchar | 15 | 用户编码 |
userName | varchar | 15 | 用户名称 |
userPassword | varchar | 15 | 用户密码 |
gender | int | 10 | 性别(1:女、 2:男) |
birthday | date | 0 | 出生日期 |
phone | varchar | 15 | 手机 |
address | varchar | 30 | 地址 |
userRole | int | 10 | 用户角色(取自角色表-角色id) |
createdBy | bigint | 20 | 创建者(userId) |
creationDate | datetime | 0 | 创建时间 |
modifyBy | bigint | 20 | 更新者(userId) |
modifyDate | datetime | 0 | 更新时间 |
smbms_role角色表
名称 | 类型 | 长度 | 描述 |
---|---|---|---|
id | bigint | 20 | 主键ID |
roleCode | varchar | 15 | 角色编码 |
roleName | varchar | 15 | 角色名称 |
createdBy | bigint | 20 | 创建者 |
creationDate | datetime | 0 | 创建时间 |
modifyBy | bigint | 20 | 修改者 |
modifyDate | datetime | 0 | 修改时间 |
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.0.5version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelper-spring-boot-starterartifactId>
<version>1.4.1version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
server:
port: 80
# mysql
spring:
datasource:
username: root
password: 123
driver-class-name: com.mysql.cj.jdbc.Driver
# zeroDateTimeBehavior=CONVERT_TO_NULL 处理时分秒出行00:00:00
url: jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&zeroDateTimeBehavior=CONVERT_TO_NULL
mybatis-plus:
configuration:
# 配置日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath:/mapper/*.xml
# 分页配置
pagehelper:
helper-dialect: mysql #数据库类型
reasonable: true # 分页参数合理化
support-methods-arguments: true #支持通过mapper接口参数来传递分页参数
pojo、service、Impl、controllermapper都由这个类生成 无需自己再创建
package com.kk;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
// 代码自动生成器
public class CodeTest {
public static void main(String[] args) {
// 1、创建代码生成器对象
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
// 此处建议写项目/src/main/java源代码的绝对路径
gc.setOutputDir(projectPath+ "/src/main/java");
gc.setAuthor("堃琪"); // 生成注释时的作者
gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I
gc.setIdType(IdType.AUTO); //主键策略自增
gc.setDateType(DateType.ONLY_DATE); //定义生成的实体类中日期类型
// 如果开启Swagger,要引入相应的包
gc.setSwagger2(true); //开启Swagger2模式
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/ssmbuild?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
// 此处要注意:parent + moduleName 为包的名字,在这个包下,创建对应的controller...
pc.setModuleName("blog"); //模块名
pc.setParent("com.kk"); // 放的包的路径
pc.setController("controller"); // controller层包名
pc.setEntity("entity"); // 实体类包名
pc.setService("service"); // service包名
pc.setMapper("mapper"); // mapper包名
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
// 设置要映射的表名
strategy.setInclude("smbms_role","smbms_user");
// 数据库下划线至实体类属性支持驼峰命名
strategy.setNaming(NamingStrategy.underline_to_camel);
//列名数据库下划线至实体类属性支持驼峰命名
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 实体类自动lombok
strategy.setRestControllerStyle(true); // controller可以使用restful
strategy.setControllerMappingHyphenStyle(true); //url中驼峰转连字符_(localhost:8080/hello_a)
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
package com.kk.blog.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.format.annotation.DateTimeFormat;
/**
*
*
*
*
* @author 堃琪
* @since 2022-12-28
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="SmbmsUser对象", description="")
public class SmbmsUser implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "用户编码")
@TableField("userCode")
private String userCode;
@ApiModelProperty(value = "用户名称")
@TableField("userName")
private String userName;
@ApiModelProperty(value = "用户密码")
@TableField("userPassword")
private String userPassword;
@ApiModelProperty(value = "性别(1:女、 2:男)")
private Integer gender;
@DateTimeFormat(pattern = "yyyy-MM-dd")
@ApiModelProperty(value = "出生日期")
private Date birthday;
@ApiModelProperty(value = "手机")
private String phone;
@ApiModelProperty(value = "地址")
private String address;
@ApiModelProperty(value = "用户角色(取自角色表-角色id)")
@TableField("userRole")
private Integer userRole;
@ApiModelProperty(value = "创建者(userId)")
@TableField("createdBy")
private Long createdBy;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建时间")
@TableField("creationDate")
private Date creationDate;
@ApiModelProperty(value = "更新者(userId)")
@TableField("modifyBy")
private Long modifyBy;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "更新时间")
@TableField("modifyDate")
private Date modifyDate;
}
package com.kk.blog.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
*
*
*
*
* @author 堃琪
* @since 2022-12-28
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="SmbmsRole对象", description="")
public class SmbmsRole implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "主键ID")
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "角色编码")
@TableField("roleCode")
private String roleCode;
@ApiModelProperty(value = "角色名称")
@TableField("roleName")
private String roleName;
@ApiModelProperty(value = "创建者")
@TableField("createdBy")
private Long createdBy;
@ApiModelProperty(value = "创建时间")
@TableField("creationDate")
private Date creationDate;
@ApiModelProperty(value = "修改者")
@TableField("modifyBy")
private Long modifyBy;
@ApiModelProperty(value = "修改时间")
@TableField("modifyDate")
private Date modifyDate;
}
使用的是pageHelper的分页插件
package com.kk.blog.entity;
import lombok.Data;
import java.util.Date;
/*
* 连表查询的数据
* */
@Data
public class SmbSm {
private Long id;
private String userCode;
private String userName;
private String userPassword;
private Integer gender;
private Date birthday;
private String phone;
private String address;
private Integer userRole;
private Date creationDate;
private String roleName;
}
package com.kk.blog.mapper;
import com.kk.blog.entity.SmbSm;
import com.kk.blog.entity.SmbmsUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
*
* Mapper 接口
*
*
* @author 堃琪
* @since 2022-12-28
*/
@Repository
public interface SmbmsUserMapper extends BaseMapper<SmbmsUser> {
/*
* 连表查询信息
* */
List<SmbSm> find();
}
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kk.blog.mapper.SmbmsUserMapper">
<select id="find" resultType="com.kk.blog.entity.SmbSm">
select * from ssmbuild.smbms_user u,ssmbuild.smbms_role r
where u.userRole = r.id order by u.id asc
select>
mapper>
package com.kk.blog.service;
import com.kk.blog.entity.SmbSm;
import com.kk.blog.entity.SmbmsUser;
import com.baomidou.mybatisplus.extension.service.IService;
import com.kk.blog.mapper.SmbmsUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
*
* 服务类
*
*
* @author 堃琪
* @since 2022-12-28
*/
public interface SmbmsUserService extends IService<SmbmsUser> {
/*
* 连表查询信息
* */
List<SmbSm> find();
}
package com.kk.blog.service.impl;
import com.kk.blog.entity.SmbSm;
import com.kk.blog.entity.SmbmsUser;
import com.kk.blog.mapper.SmbmsUserMapper;
import com.kk.blog.service.SmbmsUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*
* 服务实现类
*
*
* @author 堃琪
* @since 2022-12-28
*/
@Service
public class SmbmsUserServiceImpl extends ServiceImpl<SmbmsUserMapper, SmbmsUser> implements SmbmsUserService {
@Autowired
private SmbmsUserMapper mapper;
@Override
public List<SmbSm> find() {
return mapper.find();
}
}
package com.kk.blog.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kk.blog.entity.SmbSm;
import com.kk.blog.entity.SmbmsUser;
import com.kk.blog.service.SmbmsUserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
/**
*
* 前端控制器
*
*
* @author 堃琪
* @since 2022-12-28
*/
@Controller
@RequestMapping("/user")
public class SmbmsUserController {
@Autowired
private SmbmsUserService service;
/*
* 跳转新增
* */
@RequestMapping("/toadd")
public String toadd(){
return "add";
}
/*
* 跳转修改
* */
@RequestMapping("/tosave")
public String tosave(Model model,Integer id){
SmbmsUser smbmsUser = service.getById(id);
model.addAttribute("smbmsUser",smbmsUser);
return "save";
}
/*
* 查询信息并分页
* */
@RequestMapping({"/","/list"})
public String list(@RequestParam(defaultValue = "1") Integer pageNo,Model model){
PageHelper.startPage(pageNo,5);
List<SmbSm> list = service.find();
PageInfo<SmbSm> pageInfo = new PageInfo<>(list);
model.addAttribute("pageInfo",pageInfo);
return "list";
}
/*
* 删除
* */
@RequestMapping("/del/{id}")
public String delById(@PathVariable Long id){
boolean b = service.removeById(id);
if (b){
return "redirect:/user/list";
}else {
return "404";
}
}
/*
*
* 新增
* */
@PostMapping("/add")
public String add(SmbmsUser user){
user.setCreationDate(new Date());
user.setCreatedBy(1L);
user.setModifyDate(new Date());
user.setModifyBy(1L);
boolean save = service.save(user);
if (save){
return "redirect:/user/list";
}else {
return "404";
}
}
/*
* 修改
* */
@PostMapping("/save")
public String save(SmbmsUser user){
System.out.println(user);
user.setModifyDate(new Date());
boolean save = service.updateById(user);
if (save){
return "redirect:/user/list";
}else {
return "404";
}
}
}
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<h5 align="center"><a th:href="@{toadd}"><input type="button" value="新增">a>h5>
<table border="1px" align="center">
<tr align="center">
<td>编号td>
<td>用户编码td>
<td>用户名称td>
<td>性别td>
<td>出生日期td>
<td>手机td>
<td>地址td>
<td>用户角色td>
<td>创建时间td>
<td>操作td>
tr>
<tr align="center" th:each="smb:${pageInfo.list}">
<td th:text="${smb.id}">td>
<td th:text="${smb.userCode}">td>
<td th:text="${smb.userName}">td>
<td>
<a th:if="${smb.gender == 1}">女a>
<a th:if="${smb.gender == 2}">男a>
td>
<td th:text="${#dates.format(smb.birthday,'yyyy-MM-dd')}">td>
<td th:text="${smb.phone}">td>
<td th:text="${smb.address}">td>
<td th:text="${smb.userRole}">td>
<td th:text="${#dates.format(smb.creationDate,'yyyy-MM-dd HH:mm:ss')}">td>
<td>
<a th:href="@{'del/'+${smb.id}}">删除a>
<a th:href="@{'tosave?id='+${smb.id}}">修改a>
td>
tr>
<tr align="center">
<td colspan="10">
当前页:<b th:text="${pageInfo.pageNum}">b>
总页数:<b th:text="${pageInfo.pages}">b>
总条数:<b th:text="${pageInfo.total}">b>
<a th:href="@{'/user/list?pageNo='+${pageInfo.navigateFirstPage}}">首页a>
<a th:if="${pageInfo.hasPreviousPage == true}" th:href="@{'/user/list?pageNo='+${pageInfo.prePage}}">上一页a>
<a th:if="${pageInfo.hasNextPage == true}" th:href="@{'/user/list?pageNo='+${pageInfo.nextPage}}">下一页a>
<a th:href="@{'/user/list?pageNo='+${pageInfo.navigateLastPage}}">末页a>
td>
tr>
table>
body>
html>
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form th:action="@{add}" method="post">
<table align="center">
<tr>
<td>用户编码:td>
<td><input type="text" name="userCode">td>
tr>
<tr>
<td>用户名称:td>
<td><input type="text" name="userName">td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="userPassword">td>
tr>
<tr>
<td>性别:td>
<td>
<input type="radio" name="gender" value="1">女
<input type="radio" name="gender" value="2">男
td>
tr>
<tr>
<td>出生日期:td>
<td><input type="text" name="birthday">td>
tr>
<tr>
<td>手机:td>
<td><input type="text" name="phone">td>
tr>
<tr>
<td>地址:td>
<td><input type="text" name="address">td>
tr>
<tr>
<td>用户角色:td>
<td>
<select name="userRole">
<option value="" selected>--请选择--option>
<option value="1">系统管理员option>
<option value="2">经理option>
<option value="3">普通员工option>
select>
td>
tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="新增">
td>
tr>
table>
form>
body>
html>
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form th:action="@{save}" method="post">
<table align="center">
<tr>
<input type="hidden" name="id" th:value="${smbmsUser.id}">
<td>用户编码:td>
<td><input type="text" name="userCode" th:value="${smbmsUser.userCode}">td>
tr>
<tr>
<td>用户名称:td>
<td><input type="text" name="userName" th:value="${smbmsUser.userName}">td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="userPassword" th:value="${smbmsUser.userPassword}">td>
tr>
<tr>
<td>性别:td>
<td>
<input type="radio" name="gender" value="1" th:checked="${smbmsUser.gender == 1}">女
<input type="radio" name="gender" value="2" th:checked="${smbmsUser.gender == 2}">男
td>
tr>
<tr>
<td>出生日期:td>
<td><input type="text" name="birthday" th:value="${#dates.format(smbmsUser.birthday,'yyyy-MM-dd')}">td>
tr>
<tr>
<td>手机:td>
<td><input type="text" name="phone" th:value="${smbmsUser.phone}">td>
tr>
<tr>
<td>地址:td>
<td><input type="text" name="address" th:value="${smbmsUser.address}">td>
tr>
<tr>
<td>用户角色:td>
<td>
<select name="userRole">
<option value="" selected>--请选择--option>
<option value="1" th:selected="${smbmsUser.userRole == 1}">系统管理员option>
<option value="2" th:selected="${smbmsUser.userRole == 2}">经理option>
<option value="3" th:selected="${smbmsUser.userRole == 3}">普通员工option>
select>
td>
tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="修改">
td>
tr>
table>
form>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<div align="center"><h1>404h1>div>
body>
html>