快速上手MybatisPlus

作者 : 开心源码 本文共7332个字,预计阅读时间需要19分钟 发布时间: 2022-05-12 共255人阅读

首先附上mybatis-plus官方文档
本篇参考官方文档记录spring mvc项目接入mybatis plus的全流程及少量问题的处理方案,建议优先参考官方文档
开始之前,假设数据库已建好并已能正常访问

依赖配置

此处使用maven,gradle参考gradle依赖配置

核心依赖

查看最新版本

<dependency>    <groupId>com.baomidou</groupId>    <artifactId>mybatis-plus</artifactId>    <version>3.1.0</version></dependency>

!!!注:如之前已引入mybatis相关依赖,请去除,mybatis plus会自行管理

代码生成器相关依赖

如不需要代码生成,请跳过

  • AutoGenerator 查看最新版本

    <dependency>  <groupId>com.baomidou</groupId>  <artifactId>mybatis-plus-generator</artifactId>  <version>3.1.0</version></dependency>
  • 模版引擎,这里选择freemarker供生成器使用

    <dependency>   <groupId>org.freemarker</groupId>   <artifactId>freemarker</artifactId>   <version>2.3.23</version></dependency>
  • lombok,使用注解代替set-get方法

    <dependency>   <groupId>org.projectlombok</groupId>   <artifactId>lombok</artifactId>   <version>1.18.2</version>   <scope>provided</scope></dependency>

代码生成

要使用此功能,需增加代码生成器相关依赖

代码生成器

根据官方代码改了个较为简洁方便适合懒人直接使用的生成器, 如需更多配置可查看官方生成器模版或者参考文末附的全配置项自行配置

import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.config.DataSourceConfig;import com.baomidou.mybatisplus.generator.config.GlobalConfig;import com.baomidou.mybatisplus.generator.config.PackageConfig;import com.baomidou.mybatisplus.generator.config.StrategyConfig;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;/** * @description: 代码生成器 * @author: 04637@163.com * @date: 2019/3/3 **/public class CodeGenerator {    public static void main(String[] args) {        // ================= 必需修改的配置 start =================        // 数据源配置        String jdbcUrl = "jdbc:mysql://localhost:3306/deva?serverTimezone=Asia/Shanghai&useUnicode=true&useSSL=false&characterEncoding=utf8";        String jdbcDriver = "com.mysql.cj.jdbc.Driver";        String jdbcUsername = "root";        String jdbcPassword = "123456";        // 父级包名配置        String parentPackage = "com.ty.mp";        // 生成代码的 @author 值        String author = "04637@163.com";        // 要生成代码的表名配置        String[] tables = {                "question_info",                "answer_info",                "message_info",        };        // ================= 必需修改的配置 end =================        AutoGenerator mpg = new AutoGenerator();        // 全局配置        GlobalConfig gc = new GlobalConfig();        String projectPath = System.getProperty("user.dir");        gc.setOutputDir(projectPath + "/src/main/java");        gc.setAuthor(author);        gc.setBaseResultMap(true);        gc.setBaseColumnList(true);        // 生成完毕后能否打开输出目录        gc.setOpen(false);        // 为true时生成entity将继承Model类,单类就可完成基于单表的业务逻辑操作,按需开启        gc.setActiveRecord(false);        mpg.setGlobalConfig(gc);        // 数据源配置        DataSourceConfig dsc = new DataSourceConfig();        dsc.setUrl(jdbcUrl);        dsc.setDriverName(jdbcDriver);        dsc.setUsername(jdbcUsername);        dsc.setPassword(jdbcPassword);        mpg.setDataSource(dsc);        // 包配置        PackageConfig pc = new PackageConfig();        // 父级包名,按需修改        pc.setParent(parentPackage);        // 设置板块名, 会在parent包下生成一个指定的板块包        pc.setModuleName(null);        mpg.setPackageInfo(pc);        // 策略配置        StrategyConfig strategy = new StrategyConfig();        strategy.setNaming(NamingStrategy.underline_to_camel);        strategy.setColumnNaming(NamingStrategy.underline_to_camel);        strategy.setRestControllerStyle(false);        strategy.setInclude(tables);        strategy.setSuperEntityColumns("id");        // Controller驼峰连字符,如开启,则requestMapping由 helloWorld 变为 hello-world 默认false        strategy.setControllerMappingHyphenStyle(false);        strategy.setTablePrefix(pc.getModuleName() + "_");        // 开启后将使用lombok注解代替set-get方法,false则生成set-get方法        strategy.setEntityLombokModel(true);        // 在实体类中移除is前缀        strategy.setEntityBooleanColumnRemoveIsPrefix(true);        mpg.setStrategy(strategy);        mpg.setTemplateEngine(new FreemarkerTemplateEngine());        mpg.execute();    }}

执行后会生成这些文件

生成结果

可将生成的xml放到resources目录或者者配置xml目录为resource目录方便扫描

配置启用mybatis-plus

mapperScanner配置

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">    <property name="basePackage" value="你的mapper目录"/></bean>

sqlSessionFactory配置

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">    <property name="dataSource" ref="dataSource"/>    <property name="mapperLocations" value="mapper xml的资源路径"/></bean>

CRUD接口

mapper CRUD接口

生成的mapper接口会继承BaseMapper接口,查看mapper CRUD接口支持的操作

service CRUD接口

生成的service接口会继承 IService接口,查看service CRUD接口支持的操作

条件构造器

QueryWrapper<TagInfo> queryWrapper = new QueryWrapper<>();queryWrapper.eq("uk_name", tagName);TagInfo newTag = tagInfoMapper.selectOne(queryWrapper);

查看条件构造器所有条件写法

分页插件

待升级

问题记录及处理

生成的@Data @Accessors等注解是什么意思?

  • 有了@Data注解就无需再写那些get set方法了
  • @Accessors(chain = true) chain为true时,set方法会return该对象,false时则return void
  • @EqualsAndHashCode(callSuper = false) 会自动生成equals 和 hashCode方法,callSuper = false时不会用super的equals比较

已经有了@Data注解,却不能调用set get方法?

需要安装插件 IDEA为例:
File->settings->Plugins 查找lombok plugin安装

待升级

附:生成器全配置项

GlobalConfig 全局配置项

```/** * 生成文件的输出目录【默认 D 盘根目录】 */private String outputDir = "D://";/** * 能否覆盖已有文件 */private boolean fileOverride = false;/** * 能否打开输出目录 */private boolean open = true;/** * 能否在xml中增加二级缓存配置 */private boolean enableCache = false;/** * 开发人员 */private String author;/** * 开启 Kotlin 模式 */private boolean kotlin = false;/** * 开启 swagger2 模式 */private boolean swagger2 = false;/** * 开启 ActiveRecord 模式 */private boolean activeRecord = false;/** * 开启 BaseResultMap */private boolean baseResultMap = false;/** * 时间类型对应策略 */private DateType dateType = DateType.TIME_PACK;/** * 开启 baseColumnList */private boolean baseColumnList = false;/** * 各层文件名称方式,例如: %sAction 生成 UserAction * %s 为占位符 */private String entityName;private String mapperName;private String xmlName;private String serviceName;private String serviceImplName;private String controllerName;/** * 指定生成的主键的ID类型 */private IdType idType;```

StrategyConfig策略配置项

```/** * 能否大写命名 */private boolean isCapitalMode = false;/** * 能否跳过视图 */private boolean skipView = false;/** * 数据库表映射到实体的命名策略 */private NamingStrategy naming = NamingStrategy.no_change;/** * 数据库表字段映射到实体的命名策略 * <p>未指定按照 naming 执行</p> */private NamingStrategy columnNaming = null;/** * 表前缀 */@Setter(AccessLevel.NONE)private String[] tablePrefix;/** * 字段前缀 */@Setter(AccessLevel.NONE)private String[] fieldPrefix;/** * 自己设置继承的Entity类全称,带包名 */@Setter(AccessLevel.NONE)private String superEntityClass;/** * 自己设置基础的Entity类,公共字段 */@Setter(AccessLevel.NONE)private String[] superEntityColumns;/** * 自己设置继承的Mapper类全称,带包名 */private String superMapperClass = ConstVal.SUPER_MAPPER_CLASS;/** * 自己设置继承的Service类全称,带包名 */private String superServiceClass = ConstVal.SUPER_SERVICE_CLASS;/** * 自己设置继承的ServiceImpl类全称,带包名 */private String superServiceImplClass = ConstVal.SUPER_SERVICE_IMPL_CLASS;/** * 自己设置继承的Controller类全称,带包名 */private String superControllerClass;/** * 需要包含的表名,允许正则表达式(与exclude二选一配置) */@Setter(AccessLevel.NONE)private String[] include = null;/** * 需要排除的表名,允许正则表达式 */@Setter(AccessLevel.NONE)private String[] exclude = null;/** * 【实体】能否生成字段常量(默认 false)<br> * -----------------------------------<br> * public static final String ID = "test_id"; */private boolean entityColumnConstant = false;/** * 【实体】能否为构建者模型(默认 false)<br> * -----------------------------------<br> * public User setName(String name) { this.name = name; return this; } */private boolean entityBuilderModel = false;/** * 【实体】能否为lombok模型(默认 false)<br> * <a href="https://projectlombok.org/">document</a> */private boolean entityLombokModel = false;/** * Boolean类型字段能否移除is前缀(默认 false)<br> * 比方 : 数据库字段名称 : 'is_xxx',类型为 : tinyint. 在映射实体的时候则会去掉is,在实体类中映射最终结果为 xxx */private boolean entityBooleanColumnRemoveIsPrefix = false;/** * 生成 <code>@RestController</code> 控制器 * <pre> *      <code>@Controller</code> -> <code>@RestController</code> * </pre> */private boolean restControllerStyle = false;/** * 驼峰转连字符 * <pre> *      <code>@RequestMapping("/managerUserActionHistory")</code> -> <code>@RequestMapping("/manager-user-action-history")</code> * </pre> */private boolean controllerMappingHyphenStyle = false;/** * 能否生成实体时,生成字段注解 */private boolean entityTableFieldAnnotationEnable = false;/** * 乐观锁属性名称 */private String versionFieldName;/** * 逻辑删除属性名称 */private String logicDeleteFieldName;/** * 表填充字段 */private List<TableFill> tableFillList = null;```

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 快速上手MybatisPlus

发表回复