Springboot整合MybatisPlus(超详细)完整教程~
新建springboot项⽬
开发⼯具:idea2019.2,maven3
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- mybatis plus 代码⽣成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
server:
port: 8081
servlet:
context-path: /
spring:
datasource:
driver-class-name: sql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true    username: root
password: lyja
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
serialization:
write-dates-as-timestamps: false
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*l
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
mybatisplus分页插件MybatisPlusConfig:
f;
import sion.plugins.PaginationInterceptor;
import t.annotation.Bean;
import t.annotation.Configuration;
/**
* 配置分页插件
*
*/
@Configuration
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
mybatisplus⾃动⽣成代码GeneratorCodeConfig.java:
f;
import ptions.MybatisPlusException;
import lkit.StringUtils;
import ator.AutoGenerator;
import fig.*;
import fig.rules.NamingStrategy;
import ine.FreemarkerTemplateEngine;
import java.util.Scanner;
/**
* ⾃动⽣成mybatisplus的相关代码
*/
public class GeneratorCodeConfig {
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输⼊" + tip + ":");
System.out.String());
if (scanner.hasNext()) {
String ipt = ();
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 = Property("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("astupidcoder");
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC&useUnicode=true&characterEnc
oding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");        dsc.setDriverName("sql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("lyja");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模块名"));
pc.setParent("ample");
pc.setEntity("model.auto");
pc.setMapper("mapper.auto");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// ⾃定义配置
//        InjectionConfig cfg = new InjectionConfig() {
//            @Override
//            public void initMap() {
//                // to do nothing
//            }
//        };
// 如果模板引擎是 freemarker
//        String templatePath = "/l.ftl";
/
/ 如果模板引擎是 velocity
// String templatePath = "/l.vm";
// ⾃定义输出配置
//        List<FileOutConfig> focList = new ArrayList<>();
// ⾃定义配置会被优先输出
//        focList.add(new FileOutConfig(templatePath) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // ⾃定义输出⽂件名,如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发⽣变化!!
//                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
//                        + "/" + EntityName() + "Mapper" + StringPool.DOT_XML;
//            }
//        });
/*
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断⾃定义⽂件夹是否需要创建
checkDir("调⽤默认⽅法创建的⽬录");
return false;
}
});
*/
//        cfg.setFileOutConfigList(focList);
/
/        mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置⾃定义输出模板
//指定⾃定义模板路径,注意不要带上.ftl/.vm, 会根据使⽤的模板引擎⾃动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("sion.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setEntityLombokModel(true);
// 公共⽗类
//        strategy.setSuperControllerClass("com.baomidou.antmon.BaseController");
// 写于⽗类中的公共字段
//        strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英⽂逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.ModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
}
}
测试
建表:
执⾏GeneratorCodeConfig.java⽂件,输⼊表名user:
解决⽅法:在数据库连接中配置添加allowPublicKeyRetrieval=true
查看⽣成的⽂件;
添加扫描mapper注解
启动springboot的application启动类:会报错,提⽰不到mapper⽂件,我们需要在springboot启动类上添加扫描mapper的注解:ample;
batis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("ample.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
UserController.java中新增接⼝:
@Autowired
private IUserService userService;
@PostMapping("/getUser")
public User getUser(){
ById(1);
}
postman测试:
没问题。
上⾯是mybatisplus测试成功,下⾯我们继续测试我们⾃⼰写的sql是否成功。
在resources⽬录下新建mapper⽂件夹,新建l⽂件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd">
<mapper namespace="ample.mapper.auto.UserMapper">
<!-- 查⽤户信息 -->
select * from user
</select>
</mapper>
UserMapper.java
ample.mapper.auto;
import apper.BaseMapper;
del.auto.User;
import java.util.List;
/**
* <p>
*  Mapper 接⼝
* </p>
*
* @author astupidcoder
* @since 2020-05-13
*/
public interface UserMapper extends BaseMapper<User> {
public List<User>findAllUser();
}
IUserService:
ample.service;
import sion.service.IService;
del.auto.User;
import java.util.List;
/**
* <p>
*  服务类
* </p>
*
* @author astupidcoder
* @since 2020-05-13
*/
public interface IUserService extends IService<User> {
public List<User> findAllUser();
}
UseServiceImpl.java:
ample.service.impl;
del.auto.User;
ample.mapper.auto.UserMapper;
ample.service.IUserService;
import sion.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
*  服务实现类
* </p>
*
* @author astupidcoder
* @since 2020-05-13
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {    @Autowired
private UserMapper userMapper;
@Override
public List<User> findAllUser() {
return userMapper.findAllUser();
}
}
UserController.java:
ller;
del.auto.User;
ample.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* <p>
*  前端控制器
*
* @author astupidcoder
* @since 2020-05-13
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@PostMapping("/getUser")
public User getUser(){
ById(1);
}
@PostMapping("/findAllUser")
public List<User> findAllUser(){
return userService.findAllUser();
}
}
测试findAllUser接⼝:
常⽤的⼯具类:
ResultInfo.java
f;
import lombok.Data;
import java.io.Serializable;
/**
*返回结果类统⼀封装
*/
@Data
public class ResultInfo implements Serializable {    // 状态码
private Integer code;
// 消息
private String message;
// 数据对象
private Object result;
private Integer total;
/**
* ⽆参构造器
*/
public ResultInfo() {
super();
}
public ResultInfo(Status status) {
super();
}
public ResultInfo result(Object result) {
return this;
}
public ResultInfo message(String message) {
return this;
}
public ResultInfo total(Integer total) {
return this;
}
/**
* 只返回状态,状态码,消息
*
* @param code
* @param message
spring boot选择题
*/
public ResultInfo(Integer code, String message) {        super();
}
/**
* 只返回状态,状态码,数据对象
*
* @param code
* @param result
*/
public ResultInfo(Integer code, Object result) {        super();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。