1.MyBatis与SpringBoot整合
1.1.新建模块spboot03
1.2.在pom.xml添加mysql驱动
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
1.3.application.yml中添加内容(先把application转换成yml)
mybatis:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.example.spboot03.entity
server:
port: 8080
spring:
application:
name: spboot03
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
logging:
level:
com.example.spboot03: debug
1.4.代码生成插件
resources添加jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
resources中添加generatorConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/>
<!--指定数据库jdbc驱动jar包的位置-->
<!-- <classPathEntry location="D:\\SoftwareInstallPath\\repository\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>-->
<!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.example.spboot03.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 02 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.example.spboot03.mapper"
targetProject="src/main/resources/mappers">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 03 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.example.spboot03.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 配置表信息 -->
<!-- schema即为数据库名 -->
<!-- tableName为对应的数据库表 -->
<!-- domainObjectName是要生成的实体类 -->
<!-- enable*ByExample是否生成 example类 -->
<!--<table schema="" tableName="t_book" domainObjectName="Book"-->
<!--enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false">-->
<!--<!– 忽略列,不生成bean 字段 –>-->
<!--<!– <ignoreColumn column="FRED" /> –>-->
<!--<!– 指定列的java数据类型 –>-->
<!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>-->
<!--</table>-->
<table schema="" tableName="customer" domainObjectName="Customer"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
</context>
</generatorConfiguration>
pom.xml中添加插件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<dependencies>
<!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
</dependencies>
<configuration>
<overwrite>true</overwrite>
</configuration>
</plugin>
点击生成代码
新建一个controller包,添加JdbcController
package com.example.spboot03.controller;
import com.example.spboot03.mapper.CustomerMapper;
import com.example.spboot03.model.Customer;
import org.springframework.beans.factory.annotation.Autowired;
@RestController
@RequestMapping("/jdbc")
public class JdbcController {
@Autowired
public CustomerMapper customerMapper;
@GetMapping("/get")
public Customer list(Integer cid) {
return customerMapper.selectByPrimaryKey(cid);
}
@DeleteMapping("/delete")
public int delete(Integer cid) {
return customerMapper.deleteByPrimaryKey(cid);
}
@PostMapping("/add")
public int add(Customer customer) {
return customerMapper.insertSelective(customer);
}
}
修改启动类的内容
package com.example.spboot03;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.spboot03.mapper")
@SpringBootApplication
public class Spboot03Application {
public static void main(String[] args) {
SpringApplication.run(Spboot03Application.class, args);
}
}
启动项目,使用Eolink测试
2.MyBatis-Plus与SpringBoot整合
2.1.新建模块spboot03-mp
2.2.pom.xml中添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
2.3.application.yml中添加内容
server:
port: 8080
spring:
application:
name: spboot03-mp
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8
username: root
password: root
logging:
level:
com.example.demo: debug
mybatis-plus:
mapper-locations: classpath:mappers/**/*.xml
type-aliases-package: com.example.spboot03mp.model
2.4.MyBatis-Plus代码生成类
package com.example.spboot03mp;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* mybatis-plus代码生成
*/
public class MPGenerator {
/**
* <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.isNotBlank(ipt)) {
if ("quit".equals(ipt)) return "";
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 1.全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir") + "/spboot03-mp";
System.out.println(projectPath);
gc.setOutputDir(projectPath + "/src/main/java");
gc.setOpen(false);
gc.setBaseResultMap(true);//生成BaseResultMap
gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(true);// XML columList
//gc.setSwagger2(true); //实体属性 Swagger2 注解
gc.setAuthor("lky");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
gc.setIdType(IdType.AUTO);
mpg.setGlobalConfig(gc);
// 2.数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setUrl("jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 3.包配置
PackageConfig pc = new PackageConfig();
String moduleName = scanner("模块名(quit退出,表示没有模块名)");
if (StringUtils.isNotBlank(moduleName)) {
pc.setModuleName(moduleName);
}
pc.setParent("com.example.spboot03mp")
.setMapper("mapper")
.setService("service")
.setController("controller")
.setEntity("model");
mpg.setPackageInfo(pc);
// 4.自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
if (StringUtils.isNotBlank(pc.getModuleName())) {
return projectPath + "/src/main/resources/mappers/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
} else {
return projectPath + "/src/main/resources/mappers/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 5.策略配置
StrategyConfig strategy = new StrategyConfig();
// 表名生成策略(下划线转驼峰命名)
strategy.setNaming(NamingStrategy.underline_to_camel);
// 列名生成策略(下划线转驼峰命名)
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 是否启动Lombok配置
strategy.setEntityLombokModel(true);
// 是否启动REST风格配置
strategy.setRestControllerStyle(true);
// 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
// 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
// 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
// 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
strategy.setSuperEntityColumns("id");
// 写于父类中的公共字段plus
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
//表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user
strategy.setTablePrefix("t_", "t_sys_");
//strategy.setTablePrefix(scanner("请输入表前缀"));
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 执行
mpg.execute();
}
}
2.5运行MPGenerator
2.6.UserController添加内容
package com.example.spboot03mp.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.spboot03mp.model.User;
import com.example.spboot03mp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 前端控制器
* </p>
*
* @author lky
* @since 2023-08-08
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 查询所有
*/
@GetMapping("/list")
public List<User> list(){
return userService.list();
}
/**
* 按条件查询
*/
@GetMapping("/ListByCondition")
public List<User> ListByCondition(User user){
QueryWrapper w = new QueryWrapper();
w.like("userName",user.getUserName());
return userService.list(w);
}
/**
* 查询单个
* @param book
* @return
*/
@GetMapping("/load")
public User load(User user){
QueryWrapper w = new QueryWrapper();
w.like("id",user.getId());
return userService.getOne(w);
}
/**
* 增加
* @param user
* @return
*/
@PutMapping("/add")
public boolean add(User user){
boolean save = userService.save(user);
return save;
}
/**
* 修改
* @param book
* @return
*/
@PostMapping("/update")
public boolean update(User book){
boolean save = userService.saveOrUpdate(book);
return save;
}
/**
* 删除
* @param user
* @return
*/
@DeleteMapping("/delete")
public boolean delete(User user){
boolean save = userService.removeById(user.getId());
return save;
}
}
2.7.修改启动类中的内容
package com.example.spboot03mp;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.example.spboot03mp.mapper")
@SpringBootApplication
public class Spboot03MpApplication {
public static void main(String[] args) {
SpringApplication.run(Spboot03MpApplication.class, args);
}
}
2.8.使用Eolink测试
3.MyBatis-Plus联表查询
3.1.UserService中添加内容
/**
* 查询用户角色
* @param map map集合
* @return 查询到的列表集合
*/
List<Map> queryUserRole(Map map);
3.2.UserServiceImpl添加添加
@Autowired
private UserMapper userMapper;
/**
* 查询用户角色
*
* @param map map集合
* @return 查询到的列表集合
*/
@Override
public List<Map> queryUserRole(Map map) {
return userMapper.queryUserRole(map);
}
3.3.UserMapper中添加内容
/**
* 查询用户角色
*
* @param map map集合
* @return 查询到的列表集合
*/
List<Map> queryUserRole(Map map);
3.4.UserMapper.xml中添加内容
<select id="queryUserRole" resultType="java.util.Map">
SELECT tu.*, tr.role_name
FROM `t_user` as tu
INNER JOIN `t_role` as tr
on tu.roleId = tr.id
</select>
3.5.UserController中添加内容
// 连表查询
@GetMapping("/userRole")
public List<Map> userRole(String userName){
Map map = new HashMap();
map.put("user_name",userName);
List<Map> maps = userService.queryUserRole(map);
return maps;
}
3.6.使用Eolink测试