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)
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.1.1
mysql
mysql-connector-java
runtime
com.baomidou
mybatis-plus-boot-starter
3.3.1.tmp
com.baomidou
mybatis-plus-generator
3.3.1.tmp
org.freemarker
freemarker
2.3.29
2.mysql创建数据库,创建一个user表
3.配置数据库连接
# 驱动配置信息
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 {
// 数据库连接url
private static String dbUrl;
// 数据库驱动
private static String dbDriverName;
//数据库连接名称
private static String dbUserName;
//数据库连接密码
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);
// 数据源配置
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 focList = new ArrayList<>();
// 自定义配置会被优先输出
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();
}
/**
* 加载数据量属性配置信息
*/
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()’,系统会自动生成entity、controller、mapper、service
7.使用mybatis-plus进行增删改查
1)编写UserController.java (如果userMapper出现: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;
/**
*
* 前端控制器
*
*
* @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?"数据新增失败":"数据新增成功";
}
@RequestMapping("/delete")
@ResponseBody
private String delete(){
return userMapper.deleteById(1)==0?"数据删除失败":"数据删除成功";
}
@RequestMapping("/update")
@ResponseBody
private String update(){
User user = userMapper.selectById(1);
user.setName("Tony");
return userMapper.updateById(user)==0?"数据更新失败":"数据更新成功";
}
@RequestMapping("/query")
@ResponseBody
private String query(){
return userMapper.selectList(null).toString();
}
}
2)为防止请求返回的中文出现乱码,新增字符集拦截器设置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> 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/