SpringBoot系列—1.IDEA搭建SpringBoot框架
SpringBoot系列—2.SpringBoot攔截器篇
SpringBoot系列—3.SpringBoot Redis篇
SpringBoot系列—4.SpringBoot 整合Mybatis绒净、MP(MyBatis-Plus)
SpringBoot系列—5.SpringBoot 整合Mybatis-Plus分頁
**1.pom.xml引入依賴(mybatis、mysql-connect偿衰、mp)
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<!-- mysql-connector -->
<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.1.tmp</version>
</dependency>
<!-- mybatis-plus代碼生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1.tmp</version>
</dependency>
<!-- freemarker模板 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
2.mysql創(chuàng)建數(shù)據(jù)庫挂疆,創(chuàng)建一個user表
3.配置數(shù)據(jù)庫連接
# 驅動配置信息
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/demo?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=12345678
# mybatis掃描包
mybatis.type-aliases-package=com.example.demo.entity
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis-plus.type-aliases-package=com.example.demo.entity
mybatis-plus.mapper-locations=classpath:mybatis/mapper/*.xml
4.新建MPCodeGeneratorHelper類,使用mybatis-plus-generator進行代碼生成
package com.example.demo.helper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 代碼生成器配置
*/
public class MPCodeGeneratorHelper {
// 數(shù)據(jù)庫連接url
private static String dbUrl;
// 數(shù)據(jù)庫驅動
private static String dbDriverName;
//數(shù)據(jù)庫連接名稱
private static String dbUserName;
//數(shù)據(jù)庫連接密碼
private static String dbPassword;
public static void main(String[] args) {
// 加載DB配置信息
loadDbProperty();
// 代碼生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("Kevin");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dbUrl);
dsc.setDriverName(dbDriverName);
dsc.setUsername(dbUserName);
dsc.setPassword(dbPassword);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example.demo");
mpg.setPackageInfo(pc);
// 自定義配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
// 自定義輸出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定義配置會被優(yōu)先輸出
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
return projectPath + "/src/main/resources/mybatis/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(false);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
/**
* 加載數(shù)據(jù)量屬性配置信息
*/
private static void loadDbProperty(){
Properties props = null;
try {
Resource resource = new ClassPathResource("/application.properties");//
props = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
e.printStackTrace();
}
dbUrl = props.getProperty("spring.datasource.url","");
dbDriverName = props.getProperty("spring.datasource.driverClassName","");
dbUserName = props.getProperty("spring.datasource.username","");
dbPassword = props.getProperty("spring.datasource.password","");
}
}
5.主類新增Mapper掃描注解@MapperScan("com.example.demo.mapper")
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6.右鍵MPCodeGeneratorHelper下翎,Run ‘MPCodeGeneratorHelper.main()’缤言,系統(tǒng)會自動生成entity、controller视事、mapper胆萧、service
7.使用mybatis-plus進行增刪改查
1)編寫UserController.java (如果userMapper出現(xiàn):Could not autowire. No beans of 'UserMapper' type found.
解決辦法:在UserMapper.java添加類注解@Repository即可)
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author Kevin
* @since 2020-02-05
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
/**
* 增
* @return
*/
@RequestMapping("/add")
@ResponseBody
private String add(){
User user = new User();
user.setName("Kevin");
user.setAge(24);
user.setSex("男");
int result = userMapper.insert(user);
return result==0?"數(shù)據(jù)新增失敗":"數(shù)據(jù)新增成功";
}
@RequestMapping("/delete")
@ResponseBody
private String delete(){
return userMapper.deleteById(1)==0?"數(shù)據(jù)刪除失敗":"數(shù)據(jù)刪除成功";
}
@RequestMapping("/update")
@ResponseBody
private String update(){
User user = userMapper.selectById(1);
user.setName("Tony");
return userMapper.updateById(user)==0?"數(shù)據(jù)更新失敗":"數(shù)據(jù)更新成功";
}
@RequestMapping("/query")
@ResponseBody
private String query(){
return userMapper.selectList(null).toString();
}
}
2)為防止請求返回的中文出現(xiàn)亂碼,新增字符集攔截器設置UTF-8即可
package com.example.demo.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.StandardCharsets;
import java.util.List;
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// 解決controller返回字符串中文亂碼問題
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter)converter).setDefaultCharset(StandardCharsets.UTF_8);
}
}
}
}
3)測試mybatis-plus是否生效
8.SpringBoot整合Mybatis郑口、MP(Mybatis-Plus)完畢鸳碧,MP:https://mp.baomidou.com/