美文网首页
SpringBoot 整合MybatisPlus

SpringBoot 整合MybatisPlus

作者: 黄靠谱 | 来源:发表于2019-07-08 17:29 被阅读0次

    参考

    https://mp.baomidou.com/guide/

    最简单集成

    1. jar包依赖
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
    
    1. mapper类 继承BaseMapper
    public interface UserMapper extends BaseMapper<User> {
    }
    
    1. 启动类里面添加 mapper扫描路径
    @SpringBootApplication
    @MapperScan("com.example.demo.ssm.mapper")
    public class DemoSsmApplication {
        public static void main(String[] args) {
            SpringApplication.run(DemoSsmApplication.class, args);
        }
    }
    

    常用的集成方式

    1. 因为一般MP的方法是肯定不够用的,所以还需要依赖额外的sql,所以必须指定 mapper文件的路径.如果只依赖mp的sql的话,或者通过@Select接口可以完成的话,不需要配置下面的
    mybatis-plus.mapperLocations=classpath*:/mapper/*.xml
    mybatis-plus.typeAliasesPackage=com.example.demo.ssm.entity
    

    其它

    1. 如果表明有大小写的话,需要配置映射
    @Data
    @TableName("test_user")
    public class User {
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    

    高级特性

    https://mp.baomidou.com/config/#insertstrategy-since-3-1-2

    1. 领域模型编程
    • 实体类直接继承Model,让实体类具备一些基本的增删改查的功能
      但是新增的话,如果不使用默认的UUID的话,需要配置TableId并且指定IdType.AUTO
    @Data
    @TableName("test_user")
    public class User extends Model<User> {
        @TableId(value = "id",type = IdType.AUTO)
        private Long id;
        private String name;
        private Integer age;
        private String email;
        private String niceName;
    }
    
    • 简单的增删改查
        User test=new User();
        user.setAge(100);
        user.setName("huangzsAuto");
        user.setEmail("huang@csvw.com");
        user.setNiceName("huang_nick");
        user.insert();
        
        user.updateById();
    
        test.setId(6L);
        test.deleteById();
    
    
    1. 可以通过 mybatis-plus.configuration.mapUnderscoreToCamelCase=true 配置来实现 实体类和 数据库字段的驼峰映射,但是MP3.1 默认开启了该功能
      所以有些字段无需配置 @TableField 字段
    #mybatis-plus.configuration.mapUnderscoreToCamelCase=true
    
    1. Maven 多模块项目的扫描路径需以 classpath*: 开头 (即加载多个 jar 包下的 XML 文件),表示扫描所有模块下面的resource下面的mapper文件
    mybatis-plus.mapperLocations=classpath*:/mapper/*.xml
    

    相关文章

      网友评论

          本文标题:SpringBoot 整合MybatisPlus

          本文链接:https://www.haomeiwen.com/subject/zsuahctx.html