SpringBoot项目中MybatisPlus的使用
使用Toggl跟踪项目中时间的使用 #生活技巧# #工作学习技巧# #项目管理工具#
SpringBoot项目中MybatisPlus的使用
本文主要内容:
自动生成代码
CURD
本文在上一篇基础上做修改:使用IDEA创建一个SpringBoot项目
https://blog.csdn.net/litte_frog/article/details/82666185
使用的是springboot2.0.4版本
目前mp更新到3.0,本文都是参考官网文档
传送门:http://mp.baomidou.com/guide/quick-start.html
1、添加依赖,在pom文件中添加以下依赖:
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.1</version> </dependency>1234567891011
2、创建生成代码的类CodeGenerator,根据自己的需求修改配置策略等
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("Auto-CodeGenerator"); gc.setOpen(false); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/frog?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.setModuleName(scanner("模块名")); pc.setParent("com.frog.mybatisplus"); mpg.setPackageInfo(pc); // 自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; List<FileOutConfig> focList = new ArrayList<>(); focList.add(new FileOutConfig("/templates/mapper.xml.ftl") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 if (pc.getModuleName() == null) { return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } else { return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); mpg.setTemplate(new TemplateConfig().setXml(null)); // 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel); strategy.setColumnNaming(NamingStrategy.underline_to_camel); //strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); //strategy.setEntityLombokModel(false); //strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); strategy.setInclude(scanner("表名")); //strategy.setSuperEntityColumns("id"); strategy.setControllerMappingHyphenStyle(true); //strategy.setTablePrefix(pc.getModuleName() + "_"); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889903、执行main方法,在控制台输入表名(模块名),执行完毕后查看项目结构
项目结构
接下来做一个最简单的CURD
1、在启动类上添加MapperScan注解值为自己mapper类存放的路径,不然启动会报错
@SpringBootApplication @MapperScan("com.frog.mybatisplus.mapper") public class MybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(MybatisPlusApplication.class, args); } }12345678
2、打开生成的Controller写几个测试接口
/** * <p> * 前端控制器 * </p> * * @author Auto-CodeGenerator * @since 2018-09-13 */ @RestController @RequestMapping("/frog-test") public class FrogTestController { @Autowired private IFrogTestService frogTestService; /** * 查询 * @return */ @RequestMapping( value = "selectAll", method = RequestMethod.GET) public List<FrogTest> selectList() { QueryWrapper<FrogTest> queryWrapper = new QueryWrapper<>(); queryWrapper.orderByDesc("date"); return frogTestService.list(queryWrapper); } /** * 添加 * @return */ @RequestMapping( value = "insert", method = RequestMethod.POST) public Boolean insert(@RequestBody FrogTest entity) { return frogTestService.save(entity); } }
1234567891011121314151617181920212223242526272829303132333435363738394041将@Controller该为@RestController,因为以接口方式测试:
3、启动项目并打开PostMan测试
测试成功
4、MP的通用CURD方法
使用代码生成器生成的service都会继承IService这个类,这个类提供很多常用的方法,我们可以直接使用,方便很多。
生成的mapper都继承BaseMapper这个类:
5、自定义sql
如果我们有业务需要编写复杂的sql,也可以编写自定义sql。首先在mapper类中添加方法:
public interface FrogTestMapper extends BaseMapper<FrogTest> { /** * 自定义修改的sql * @param entity * @return */ Boolean updateMy (FrogTest entity); }12345678910
在xml中编写自定义sql:
<update id="updateMy" parameterType="com.frog.mybatisplus.entity.FrogTest"> UPDATE frog_test t SET t.state = '1' WHERE t.name = #{name} </update>123
controller中调用该方法:
@Autowired private FrogTestMapper mapper; /** * 修改:使用自己写的sql * @return */ @RequestMapping( value = "update", method = RequestMethod.POST) public Boolean update(@RequestBody FrogTest entity) { return mapper.updateMy(entity); }12345678910111213
测试报错
根据提示我们需要配置,能扫描到mapper.xml文件,在application.yml文件中增加如下配置:
mybatis-plus: mapper-locations: classpath*:mapper/*.xml type-aliases-package: com.frog.mybatisplus.entity check-config-location: true executor-type: simple global-config: refresh: true1234567
含义分别为:
config-location:
MyBatis Mapper 所对应的 XML 文件位置,如果您在 Mapper 中有自定义方法(XML 中有自定义实现),需要进行该配置,告诉 Mapper 所对应的 XML 文件位置。
type-aliases-package:
MyBaits 别名包扫描路径,通过该属性可以给包中的类注册别名,注册后在 Mapper 对应的 XML 文件中可以直接使用类名,而不用使用全限定的类名(即 XML 中调用的时候不用包含包名)。
check-config-location:
启动时是否检查 MyBatis XML 文件的存在,默认不检查。
executor-type:
通过该属性可指定 MyBatis 的执行器,MyBatis 的执行器总共有三种:
ExecutorType.SIMPLE:该执行器类型不做特殊的事情,为每个语句的执行创建一个新的预处理语句(PreparedStatement)
ExecutorType.REUSE:该执行器类型会复用预处理语句(PreparedStatement)
ExecutorType.BATCH:该执行器类型会批量执行所有的更新语句
refresh:
是否自动刷新 Mapper 对应的 XML 文件,默认不自动刷新。如果配置了该属性,Mapper 对应的 XML 文件会自动刷新,更改 XML 文件后,无需再次重启工程,由此节省大量时间。
再次启动测试,成功!
网址:SpringBoot项目中MybatisPlus的使用 https://www.yuejiaxmz.com/news/view/318910
相关内容
基于微信小程序旧物共享平台设计和实现java+springboot的项目【网站项目】基于springboot的生活信息分享平台
Springboot基于SpringBoot的宠物门诊系统6f8jy
基于SpringBoot+Vue前后端分离的在线教育平台项目
基于webGIS的大气监测系统设计
二手家电交易系统(SpringBoot,SSM,MySQL)
Springboot基于springboot的校园生活工具租赁系统cftei
基于springboot的疫情社区生活服务系统
【2024】基于springboot的健康饮食(膳食)网站课题背景、目的、意义
【网站项目】基于springboot的二手物品交易平台设计和实现