配置(mybatis-plus-boot-starter)

依赖pox.xml

<!--   数据库   -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <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.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.1</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>

配置application.yml

数据库连接:

  • useUnicode=true:启用Unicode支持
  • characterEncoding=utf8:指定字符编码utf8,防止中文乱码
  • useSSL=false:不使用SSL加密
  • serverTimezone=CTT:设置服务器时区
  • allowPublicKeyRetrieval=true:允许客户端从服务器检索公钥
  • allowMultiQueries=true:允许mybatis一个标签里写多条语句提交
  • rewriteBatchedStatements=true:启用批量语句重写,优化性能
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=CTT&allowPublicKeyRetrieval=true&allowMultiQueries=true&rewriteBatchedStatements=true
    username: XXXXX
    password: XXXXX
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  # xml文件,classpath在这儿指/resources
  mapper-locations: classpath*:com/example/producer/mapper/xml/*.xml
  global-config:
    db-config:
      # 主键类型
      id-type: id_worker
      # 字段策略
      field-strategy: not_empty
      # 数据库类型
      db-type: mysql
      # 忽略非null非empty判断,所有字段都可插入和更新
      insert-strategy: ignored
      update-strategy: ignored
  configuration:
    # 配置返回数据库(column下划线命名&&返回java实体是驼峰命名)
    map-underscore-to-camel-case: true
    # 配置返回数据库(查询结果为null时也返回键对值)
    call-setters-on-nulls: true
    # 打印SQL
    # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    # cache-enabled: false
# 只打印查询语句、不打印查询结果
logging:
  level:
    com.example.producer.mapper: debug
  file:
    path: ./log
  pattern:
    console: '%d{yyyy-MM-dd hh:mm:ss} [%thread] %-5level %logger{50} - %msg%n'
    file: '%d{yyyy-MM-dd hh:mm:ss} === [%thread] === %-5level === %logger{50} ==== %msg%n'

配置config/MybatisPlusConfig

@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        PaginationInterceptor paginationInterceptor=new PaginationInterceptor();
        return paginationInterceptor;
    }
}

程序入口@MapperScan

@MapperScan(value = "com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

自动生成代码配置(mybatis-plus-generator+velocity-engine-core)

新建类CodeGenerator

public class CodeGenerator {
    private static String author = "Lorogy";//作者名称
    private static String projectPath = System.getProperty("user.dir");
    private static String outputDir = projectPath + "/src/main/java";//生成的位置
    private static String driver = "com.mysql.cj.jdbc.Driver";//驱动,注意版本
    //连接路径,注意修改数据库名称
    private static String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8";
    private static String username = "root";//数据库用户名
    private static String password = "123456";//数据库密码
    //private static String tablePrefix = "t_";//数据库表的前缀,如t_user
    private static String parentPackage = "com.example.demo";//顶级包结构
    private static String mapper = "mapper";//数据访问层包名称
    private static String mapperXml = "mapper.xml";//控制器层包名称
    private static String service = "service";//业务逻辑层包名称
    private static String serviceImpl = "service.impl";//业务逻辑层包名称
    private static String entity = "model";//实体层包名称
    private static String controller = "controller";//控制器层包名称

    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();

        // 1. 全局配置
        GlobalConfig gConfig = new GlobalConfig();
        gConfig.setAuthor(author)//添加开发人员
                .setOutputDir(outputDir)//设置生成文件的输出目录
                .setOpen(true)//是否打开输出目录
                .setServiceName("%sService") //设置生成的service接口的名字的首字母是否为I,加%s则不生成I
                .setBaseResultMap(true)//映射文件中是否生成ResultMap配置
                .setBaseColumnList(true)//生成通用sql字段
                // .setSwagger2(true)//开启 swagger2 模式
                .setFileOverride(true);//是否开启覆盖

        // 2. 数据源配置
        DataSourceConfig dsConfig = new DataSourceConfig();
        dsConfig.setDriverName(driver)
                .setUrl(url)
                .setUsername(username)
                .setPassword(password);

        // 3. 包名策略配置
        PackageConfig pkConfig = new PackageConfig();
        pkConfig.setParent(parentPackage)//顶级包结构
                .setEntity(entity)//实体类
                .setMapper(mapper)//数据访问层
                .setXml(mapperXml)//mapper映射
                .setService(service)//业务逻辑层
                .setServiceImpl(serviceImpl)//业务逻辑层实现类
                .setController(controller);//控制器

        // 4. 策略配置
        StrategyConfig stConfig = new StrategyConfig();
        stConfig.setNaming(NamingStrategy.underline_to_camel)//设置数据库表映射到实体的命名策略,下划线转驼峰命名
                .setColumnNaming(NamingStrategy.underline_to_camel)//数据库表字段映射到实体的命名策略:下划线转驼峰命名(非必要,如果不配置则按照Naming执行)
                .setEntityLombokModel(true)//开启lombok注解
                .setRestControllerStyle(true)//生成RestController注解
                //.setControllerMappingHyphenStyle(true)//驼峰转连字符
                //.setTablePrefix(pkConfig.getModuleName() + "_")
                //.setVersionFieldName("version")//乐观锁
                .setInclude(scanner("(多个以英文逗号分割)").split(","));

        // 5. 整合配置
        mpg.setGlobalConfig(gConfig);
        mpg.setDataSource(dsConfig);
        mpg.setPackageInfo(pkConfig);
        mpg.setStrategy(stConfig);

        // 6 执行
        mpg.execute();
    }
}

运行

-可同时输入多个表名

在这里插入图片描述

  • 回车后生成目录

controller——控制器层
mapper——数据访问层
mapper.xml——mapper映射
model ——实体类
service——业务逻辑层接口
service.impl——接口实现类

分页查询(自带IPage)

实体

package com.example.demo.entity;

import lombok.Data;

@Data
public class PageEntity {
    private Integer pageNum;//请求页数
    private Integer pageSize;//请求数量
}

实现类

/**
     * @Description: 查询所有用户
     * @Param: []
     * @Return: java.util.List<com.example.demo.model.TbUser>
     */
    @Override
    public Object selectAllUser(PageEntity pageEntity) {
        IPage<TbUser> page=new Page<>(pageEntity.getPageNum(),pageEntity.getPageSize());
        page=tbUserMapper.selectPage(page,null);
        return page;
        //JSONObject jsonObject=new JSONObject();
        //jsonObject.put("current",page.getCurrent());//当前页数
        //jsonObject.put("size",page.getSize());//当前数量
        //jsonObject.put("total",page.getTotal());//总共数量
        //jsonObject.put("list",page.getRecords());//查询结果
        //return jsonObject;
    }

查询方式

通过XML查询

1.parameterType

可以是单个参数,也可以是实体对象
mapper方法参数:(Integer id)

<select id="[mapper对应方法名]" parameterType="java.lang.Integer" resultType="com.demo.entity.[返回对应实体类]">
        select * from user where id=#{id,jdbcType=INTERGER}
</select>

2.通过@Param传参

mapper方法参数:(@Param("id") Integer id,@Param("sex") String sex)

<select id="[mapper对应方法名]" parameterType="java.lang.Integer" resultType="com.demo.entity.[返回对应实体类]">
        select * from user where id=#{id} and sex=#{sex}
</select>

3.通过Map传参

mapper方法参数: (Map map)

<select id="[mapper对应方法名]" parameterType="java.lang.Integer" resultType="com.demo.entity.[返回对应实体类]">
        select * from user where id=#{id} and sex=#{sex}
</select>

4.也可以是数组或List传参

@Select方法

直接在mapper中通过@Select注解写SQL,不需要写mapper.xml

1.通过Map传参

将多个参数通过Map一次性传入

public interface RoleMapper extends BaseMapper<Role> {
   @Select(" select id,name from role where id in (select rid from user_role where uid=#{uid})")
   List<Role> getRoleList(Map record);
}

2.通过@Param传参

普通SQL

public interface MenuMapper extends BaseMapper<Menu> {
    @Select("select * from menu where id in (select mid from role_menu where rid=#{rid})")
    List<Menu> getMenuList(@Param("rid") Integer id);
}

动态SQL

public interface MenuMapper extends BaseMapper<Menu> {
    @Select("<script>"
            +"select * from menu where 1=1"
            +"<if test='rid!= null'>"
            +"and rid= #{rid}"
            +"</if>"
            +"</script>")
    List<Menu> getMenuList(@Param("rid") Integer id);
}
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐