show me the code and talk to me,做的出來更要說的明白
我是布爾bl,你的支持是我分享的動力!
1 引入
使用 MyBatis-Plus 以及 thymeleaf 實現增刪查改。效果圖在最后。
2 Mybatis-Plus
MyBatis-Plus(簡稱 MP)是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發、提高效率而生。
3 thymeleaf
一個模板語言,為后端 Springboot 的開發而生。
4 Lombok
Lombok 可以通過注解簡化代碼,他會在編譯的時候自動生成代碼,我們在源代碼是看不到他的。需要引入 maven 依賴以及安裝插件。
4.1 用途:
- @Date注解生成getter方法、setter方法、無參構造器、重寫equal方法、hashcode方法。一般應用這個注解即可。
- @NoArgsConstructor 生成無參構造器
- @AllArgsConstructor 生成包含所有參數的構造器
- @Sj4j 可以用來打印日志
以上都是類注解。
5 maven 引入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
6 造一些數據
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年齡',
`email` varchar(50) DEFAULT NULL COMMENT '郵箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4;
INSERT INTO `user` VALUES ('1', 'Jone', '18', 'test1@baomidou.com');
INSERT INTO `user` VALUES ('2', 'Jack', '20', 'test2@baomidou.com');
INSERT INTO `user` VALUES ('3', 'Tom', '28', 'test3@baomidou.com');
INSERT INTO `user` VALUES ('4', 'Sandy', '21', 'test4@baomidou.com');
INSERT INTO `user` VALUES ('5', 'w', '12', '8377@qq.com');
INSERT INTO `user` VALUES ('6', 'booleanbl', '12', '837@qq.com');
INSERT INTO `user` VALUES ('7', 'wenda', '12', '8377@qq.com');
INSERT INTO `user` VALUES ('8', 'booleanbl', '12', '83774@qq.com');
INSERT INTO `user` VALUES ('9', 'booleanbl', '12', '8377@qq.com');
INSERT INTO `user` VALUES ('10', '布爾bl', '12', '1831@163.com');
INSERT INTO `user` VALUES ('11', '布爾bl', '12', 'du@qq.com');
INSERT INTO `user` VALUES ('12', '布爾bl', '22', '8@qq.com');
7 項目結構
├─java
│ └─com
│ └─example
│ └─crud
│ ├─controller
│ ├─entity
│ ├─mapper
│ ├─service
│ │ └─impl
│ └─util
└─resources
└─templates
8 生成代碼
通過代碼將sql語句變成項目的基礎代碼。基礎代碼有實體類、控制層代碼、服務層代碼等等,減少機械操作。實現代碼后我們只需要輸入表明即可生成需要代碼。
public class CodeGenerator {
/**
* <p>
* 讀取控制台內容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請輸入正確的" + tip + "!");
}
public static void main(String[] args) {
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
// gc.setSwagger2(true); 實體屬性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 數據源配置
DataSourceConfig dsc = new DataSourceConfig();
// 填寫數據庫名稱
dsc.setUrl("jdbc:mysql://數據庫地址:3306/dev?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//包名
pc.setParent("com.example.crud");
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定義輸出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定義配置會被優先輸出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設置了前后綴、此處注意 xml 的名稱會跟着發生變化!!
return projectPath + "/src/main/java/com/example/crud/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(scanner("表名,多個英文逗號分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new VelocityTemplateEngine());
mpg.execute();
}
}
9 application.yml
編寫 application.yml 文件,實現數據庫連接以及 一些 thymeleaf 的必要配置。
spring:
datasource:
url: jdbc:mysql://IP/數據庫名
username: 用戶名
password: 密碼
driver-class-name: com.mysql.jdbc.Driver
thymeleaf:
cache: false
prefix: classpath:/templates/
check-template-location: true
suffix: .html
encoding: utf-8
servlet:
content-type: text/html
mode: HTML5
logging:
level:
com.example.crud.mapper: trace # 改成你的mapper文件所在包路徑
10 主要后端代碼
我們使用 mybatis-plus 不需要編寫 xml 就可以快速實現單表查詢。所以省略很多代碼。其中的分頁代碼可以在運行時自動加載,不需要我們編寫分頁代碼,這點給 mybatis-plus 點贊。
10.1 控制代碼
package com.example.crud.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crud.entity.User;
import com.example.crud.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author jobob
* @since 2019-12-06
*/
@Controller
@RequestMapping("/crud/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/update")
public String update(User user){
userService.updateById(user);
return "redirect:list";
}
@RequestMapping("/edit")
public String edit(Model model, Integer id){
User user = userService.getById(id);
model.addAttribute("user", user);
return "edit";
}
@RequestMapping("/delect")
public String delect(Integer id){
userService.removeById(id);
return "redirect:list";
}
@RequestMapping("/add")
public String add(@ModelAttribute User user){
userService.save(user);
return "redirect:list";
}
@RequestMapping("/list")
public String hello(Model model, @RequestParam(value = "current", required = false, defaultValue = "1") long current) {
Page<User> curPage = new Page<>();
curPage.setCurrent(current); // 當前頁
Page<User> page = userService.page(curPage);
model.addAttribute("page", page);
return "list";
}
}
10.2 分頁配置代碼
如果我們需要使用 ,mybatisplus 分頁插件,需要手動配置。
package com.example.crud.util;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @Description: 配置 mybatisplus 的分頁
* @Author: boolean
* @Date: 2020/1/6 0:07
*/
@EnableTransactionManagement
@Configuration
public class Config {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 設置請求的頁面大於最大頁后操作, true調回到首頁,false 繼續請求 默認false
// paginationInterceptor.setOverflow(false);
// 設置最大單頁限制數量,默認 500 條,-1 不受限制
// paginationInterceptor.setLimit(500);
return paginationInterceptor;
}
}
11 主要前端代碼
我們利用 thymeleaf 編寫前端代碼,可以快速解決數據前后端數據傳輸問題。
11.1 list.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div style="width:500px;margin:20px auto;text-align: center">
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>姓名</td>
<td>年齡</td>
<td>郵箱</td>
<td>編輯</td>
<td>刪除</td>
</tr>
<tr th:each="c:${page.records}">
<td th:text="${c.id}"></td>
<td th:text="${c.name}"></td>
<td th:text="${c.age}"></td>
<td th:text="${c.email}"></td>
<td><a th:href="@{/crud/user/edit(id=${c.id})}">編輯</a></td>
<td><a th:href="@{/crud/user/delect(id=${c.id})}">刪除</a></td>
</tr>
</table>
<br/>
<div>
<a th:href="@{/crud/user/list(current=1)}">[首 頁]</a>
<a th:href="@{/crud/user/list(current=${page.current-1})}">[上一頁]</a>
<a th:href="@{/crud/user/list(current=${page.current+1})}">[下一頁]</a>
</div>
<br/>
<form action="add" method="post">
姓名: <input name="name"/> <br/>
年齡: <input name="age"/> <br/>
郵箱: <input name="email"/> <br/>
<button type="submit">提交</button>
</form>
</div>
</body>
</html>
11.2 edit.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div style="margin:0px auto; width:500px">
<form action="update" method="post">
姓名: <input name="name" th:value="${user.name}"/> <br/>
年齡: <input name="age" th:value="${user.age}"/> <br/>
郵箱: <input name="email" th:value="${user.email}"/> <br/>
<input name="id" type="hidden" th:value="${user.id}"/>
<button type="submit">提交</button>
</form>
</div>
</body>
</html>
12 源碼
https://github.com/buerbl/learnSpringboot/tree/master/lsb-crub