IDEA+SpringBoot MyBatis Dynamic SQL的初体验(一)

ybatis generator在2017年12月发布了version 1.3.6,在该版本添加了新的TargetRuntime:

  MyBatis Dynamic SQL(mybatis 动态SQL)

    Mybatis Dynamic Sql与以前TargetRuntime相比较:

  1. 移除了XXXExamle类和xml文件,代价是不兼容其他的TargetRuntime
  2. java版本限制,生成器将需要运行Java 8,低版本可能会出现错误
  3. 代码逻辑相对以前,使用了 lambda表达式,是的较容易理解
  4. 移除了iBatis2代码生成的支持

本文将用Intellij IDEA为编译器,Gradle作为项目管理器(个人觉得gradle相对maven来说,代码少太多了),试用Mybatis Dynamic SQL

  第一步,安装Intellij IDEA, 请自行百度

  第二步,安装Gradle,可忽略IDEA会自行下载

  第三步,创建SpringBoot Gradle项目

    

    

    

    

    项目创建成功

    

    点击import Changes自动下包

    项目初始结构如下

    

    在resources下建立mybatis-generator.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 3         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 4 <generatorConfiguration>
 5   <!--mybatis targetRuntime选择 该测试需要MyBatis3DynamicSQL-->
 6   <context id="MySql" targetRuntime="MyBatis3DynamicSQL">
 7     <commentGenerator>
 8       <property name="suppressAllComments" value="true"/>
 9       <property name="suppressDate" value="true"/>
10     </commentGenerator>
11     <!--数据库连接-->
12     <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
13                     connectionURL="jdbc:mysql://localhost:3306/nice_test?serverTimezone=UTC&amp;useSSL=false"
14                     userId="pigge" password="123456"/>
15     <!--类型解析器-->
16     <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl">
17       <!--是否对整型进行分类-->
18       <property name="forceBigDecimals" value="true"/>
19       <!--是否试用jdk8时间类-->
20       <property name="useJSR310Types" value="true"/>
21     </javaTypeResolver>
22     <!--java实体类生成配置-->
23     <javaModelGenerator targetPackage="com.pigge.mybatistest.entity" targetProject="src\main\java">
24       <!--此属性用于选择MyBatis Generator是否将根据内省表的目录和架构为对象生成不同的Java包。-->
25       <property name="enableSubPackages" value="true"/>
26       <!--去除字段空格-->
27       <property name="trimStrings" value="true"/>
28     </javaModelGenerator>
29     <!--mapper生成配置-->
30     <javaClientGenerator type="ANNOTATEDMAPPER" targetPackage="com.pigge.mybatistest.mapper" targetProject="src\main\java">
31       <!--此属性用于选择MyBatis Generator是否将根据内省表的目录和架构为对象生成不同的Java包。-->
32       <property name="enableSubPackages" value="true"/>
33     </javaClientGenerator>
34     <!--数据表的选择-->
35     <table schema="nice_test" tableName="user"/>
36     <table schema="nice_test" tableName="role"/>
37     <table schema="nice_test" tableName="authority"/>
38     <table schema="nice_test" tableName="login_record"/>
39   </context>
40 </generatorConfiguration>

在java下新建util包和MybatisGenerator.java文件

package com.pigge.mybatistest.util;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MybatisGenerator {
    public static void main(String[] args) throws IOException, XMLParserException,
            InvalidConfigurationException, SQLException, InterruptedException {
        String classpath = MybatisGenerator.class.getResource("/").getPath();
        String filename = "mybatis-generator.xml";
        File file = new File(classpath + filename);
        if(!file.exists()){
            //找不到文件 切换路径
            classpath = classpath.replace("classes", "resources");
            file = new File(classpath + filename);
        }
        List<String> warnings = new ArrayList<>();
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(file);
        DefaultShellCallback callback = new DefaultShellCallback(true);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}

执行MybatisGenerator的main方法,将生成mybatis dynamic 代码

其样式为

实体类

package com.pigge.entity;

import java.time.LocalDateTime;
import javax.annotation.Generated;

public class Role {
    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Integer id;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String name;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private String authorityIds;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Integer createUserId;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private LocalDateTime createTime;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private LocalDateTime expireTime;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    private Boolean due;

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public Integer getId() {
        return id;
    }

    @Generated("org.mybatis.generator.api.MyBatisGenerator")
    public void setId(Integer id) {
        this.id = id;
    }

   //剩下的getter setter方法省略
}

mapper类 代码过长 不建议打开

  1 package com.pigge.mapper;
  2
  3 import static com.pigge.mapper.RoleDynamicSqlSupport.*;
  4 import static org.mybatis.dynamic.sql.SqlBuilder.*;
  5
  6 import com.pigge.entity.Role;
  7 import java.util.List;
  8 import javax.annotation.Generated;
  9 import org.apache.ibatis.annotations.DeleteProvider;
 10 import org.apache.ibatis.annotations.InsertProvider;
 11 import org.apache.ibatis.annotations.Mapper;
 12 import org.apache.ibatis.annotations.Result;
 13 import org.apache.ibatis.annotations.ResultMap;
 14 import org.apache.ibatis.annotations.Results;
 15 import org.apache.ibatis.annotations.SelectProvider;
 16 import org.apache.ibatis.annotations.UpdateProvider;
 17 import org.apache.ibatis.type.JdbcType;
 18 import org.mybatis.dynamic.sql.SqlBuilder;
 19 import org.mybatis.dynamic.sql.delete.DeleteDSL;
 20 import org.mybatis.dynamic.sql.delete.MyBatis3DeleteModelAdapter;
 21 import org.mybatis.dynamic.sql.delete.render.DeleteStatementProvider;
 22 import org.mybatis.dynamic.sql.insert.render.InsertStatementProvider;
 23 import org.mybatis.dynamic.sql.render.RenderingStrategy;
 24 import org.mybatis.dynamic.sql.select.MyBatis3SelectModelAdapter;
 25 import org.mybatis.dynamic.sql.select.QueryExpressionDSL;
 26 import org.mybatis.dynamic.sql.select.SelectDSL;
 27 import org.mybatis.dynamic.sql.select.render.SelectStatementProvider;
 28 import org.mybatis.dynamic.sql.update.MyBatis3UpdateModelAdapter;
 29 import org.mybatis.dynamic.sql.update.UpdateDSL;
 30 import org.mybatis.dynamic.sql.update.render.UpdateStatementProvider;
 31 import org.mybatis.dynamic.sql.util.SqlProviderAdapter;
 32
 33 @Mapper
 34 public interface RoleMapper {
 35     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 36     @SelectProvider(type=SqlProviderAdapter.class, method="select")
 37     long count(SelectStatementProvider selectStatement);
 38
 39     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 40     @DeleteProvider(type=SqlProviderAdapter.class, method="delete")
 41     int delete(DeleteStatementProvider deleteStatement);
 42
 43     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 44     @InsertProvider(type=SqlProviderAdapter.class, method="insert")
 45     int insert(InsertStatementProvider<Role> insertStatement);
 46
 47     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 48     @SelectProvider(type=SqlProviderAdapter.class, method="select")
 49     @ResultMap("RoleResult")
 50     Role selectOne(SelectStatementProvider selectStatement);
 51
 52     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 53     @SelectProvider(type=SqlProviderAdapter.class, method="select")
 54     @Results(id="RoleResult", value = {
 55         @Result(column="id", property="id", jdbcType=JdbcType.INTEGER, id=true),
 56         @Result(column="name", property="name", jdbcType=JdbcType.VARCHAR),
 57         @Result(column="authority_ids", property="authorityIds", jdbcType=JdbcType.VARCHAR),
 58         @Result(column="create_user_id", property="createUserId", jdbcType=JdbcType.INTEGER),
 59         @Result(column="create_time", property="createTime", jdbcType=JdbcType.TIMESTAMP),
 60         @Result(column="expire_time", property="expireTime", jdbcType=JdbcType.TIMESTAMP),
 61         @Result(column="due", property="due", jdbcType=JdbcType.BIT)
 62     })
 63     List<Role> selectMany(SelectStatementProvider selectStatement);
 64
 65     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 66     @UpdateProvider(type=SqlProviderAdapter.class, method="update")
 67     int update(UpdateStatementProvider updateStatement);
 68
 69     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 70     default QueryExpressionDSL<MyBatis3SelectModelAdapter<Long>> countByExample() {
 71         return SelectDSL.selectWithMapper(this::count, SqlBuilder.count())
 72                 .from(role);
 73     }
 74
 75     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 76     default DeleteDSL<MyBatis3DeleteModelAdapter<Integer>> deleteByExample() {
 77         return DeleteDSL.deleteFromWithMapper(this::delete, role);
 78     }
 79
 80     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 81     default int deleteByPrimaryKey(Integer id_) {
 82         return DeleteDSL.deleteFromWithMapper(this::delete, role)
 83                 .where(id, isEqualTo(id_))
 84                 .build()
 85                 .execute();
 86     }
 87
 88     @Generated("org.mybatis.generator.api.MyBatisGenerator")
 89     default int insert(Role record) {
 90         return insert(SqlBuilder.insert(record)
 91                 .into(role)
 92                 .map(id).toProperty("id")
 93                 .map(name).toProperty("name")
 94                 .map(authorityIds).toProperty("authorityIds")
 95                 .map(createUserId).toProperty("createUserId")
 96                 .map(createTime).toProperty("createTime")
 97                 .map(expireTime).toProperty("expireTime")
 98                 .map(due).toProperty("due")
 99                 .build()
100                 .render(RenderingStrategy.MYBATIS3));
101     }
102
103     @Generated("org.mybatis.generator.api.MyBatisGenerator")
104     default int insertSelective(Role record) {
105         return insert(SqlBuilder.insert(record)
106                 .into(role)
107                 .map(id).toPropertyWhenPresent("id", record::getId)
108                 .map(name).toPropertyWhenPresent("name", record::getName)
109                 .map(authorityIds).toPropertyWhenPresent("authorityIds", record::getAuthorityIds)
110                 .map(createUserId).toPropertyWhenPresent("createUserId", record::getCreateUserId)
111                 .map(createTime).toPropertyWhenPresent("createTime", record::getCreateTime)
112                 .map(expireTime).toPropertyWhenPresent("expireTime", record::getExpireTime)
113                 .map(due).toPropertyWhenPresent("due", record::getDue)
114                 .build()
115                 .render(RenderingStrategy.MYBATIS3));
116     }
117
118     @Generated("org.mybatis.generator.api.MyBatisGenerator")
119     default QueryExpressionDSL<MyBatis3SelectModelAdapter<List<Role>>> selectByExample() {
120         return SelectDSL.selectWithMapper(this::selectMany, id, name, authorityIds, createUserId, createTime, expireTime, due)
121                 .from(role);
122     }
123
124     @Generated("org.mybatis.generator.api.MyBatisGenerator")
125     default QueryExpressionDSL<MyBatis3SelectModelAdapter<List<Role>>> selectDistinctByExample() {
126         return SelectDSL.selectDistinctWithMapper(this::selectMany, id, name, authorityIds, createUserId, createTime, expireTime, due)
127                 .from(role);
128     }
129
130     @Generated("org.mybatis.generator.api.MyBatisGenerator")
131     default Role selectByPrimaryKey(Integer id_) {
132         return SelectDSL.selectWithMapper(this::selectOne, id, name, authorityIds, createUserId, createTime, expireTime, due)
133                 .from(role)
134                 .where(id, isEqualTo(id_))
135                 .build()
136                 .execute();
137     }
138
139     @Generated("org.mybatis.generator.api.MyBatisGenerator")
140     default UpdateDSL<MyBatis3UpdateModelAdapter<Integer>> updateByExample(Role record) {
141         return UpdateDSL.updateWithMapper(this::update, role)
142                 .set(id).equalTo(record::getId)
143                 .set(name).equalTo(record::getName)
144                 .set(authorityIds).equalTo(record::getAuthorityIds)
145                 .set(createUserId).equalTo(record::getCreateUserId)
146                 .set(createTime).equalTo(record::getCreateTime)
147                 .set(expireTime).equalTo(record::getExpireTime)
148                 .set(due).equalTo(record::getDue);
149     }
150
151     @Generated("org.mybatis.generator.api.MyBatisGenerator")
152     default UpdateDSL<MyBatis3UpdateModelAdapter<Integer>> updateByExampleSelective(Role record) {
153         return UpdateDSL.updateWithMapper(this::update, role)
154                 .set(id).equalToWhenPresent(record::getId)
155                 .set(name).equalToWhenPresent(record::getName)
156                 .set(authorityIds).equalToWhenPresent(record::getAuthorityIds)
157                 .set(createUserId).equalToWhenPresent(record::getCreateUserId)
158                 .set(createTime).equalToWhenPresent(record::getCreateTime)
159                 .set(expireTime).equalToWhenPresent(record::getExpireTime)
160                 .set(due).equalToWhenPresent(record::getDue);
161     }
162
163     @Generated("org.mybatis.generator.api.MyBatisGenerator")
164     default int updateByPrimaryKey(Role record) {
165         return UpdateDSL.updateWithMapper(this::update, role)
166                 .set(name).equalTo(record::getName)
167                 .set(authorityIds).equalTo(record::getAuthorityIds)
168                 .set(createUserId).equalTo(record::getCreateUserId)
169                 .set(createTime).equalTo(record::getCreateTime)
170                 .set(expireTime).equalTo(record::getExpireTime)
171                 .set(due).equalTo(record::getDue)
172                 .where(id, isEqualTo(record::getId))
173                 .build()
174                 .execute();
175     }
176
177     @Generated("org.mybatis.generator.api.MyBatisGenerator")
178     default int updateByPrimaryKeySelective(Role record) {
179         return UpdateDSL.updateWithMapper(this::update, role)
180                 .set(name).equalToWhenPresent(record::getName)
181                 .set(authorityIds).equalToWhenPresent(record::getAuthorityIds)
182                 .set(createUserId).equalToWhenPresent(record::getCreateUserId)
183                 .set(createTime).equalToWhenPresent(record::getCreateTime)
184                 .set(expireTime).equalToWhenPresent(record::getExpireTime)
185                 .set(due).equalToWhenPresent(record::getDue)
186                 .where(id, isEqualTo(record::getId))
187                 .build()
188                 .execute();
189     }
190 }

Support类 不多可以打开

 1 package com.pigge.mapper;
 2
 3 import java.sql.JDBCType;
 4 import java.time.LocalDateTime;
 5 import javax.annotation.Generated;
 6 import org.mybatis.dynamic.sql.SqlColumn;
 7 import org.mybatis.dynamic.sql.SqlTable;
 8
 9 public final class RoleDynamicSqlSupport {
10     @Generated("org.mybatis.generator.api.MyBatisGenerator")
11     public static final Role role = new Role();
12
13     @Generated("org.mybatis.generator.api.MyBatisGenerator")
14     public static final SqlColumn<Integer> id = role.id;
15
16     @Generated("org.mybatis.generator.api.MyBatisGenerator")
17     public static final SqlColumn<String> name = role.name;
18
19     @Generated("org.mybatis.generator.api.MyBatisGenerator")
20     public static final SqlColumn<String> authorityIds = role.authorityIds;
21
22     @Generated("org.mybatis.generator.api.MyBatisGenerator")
23     public static final SqlColumn<Integer> createUserId = role.createUserId;
24
25     @Generated("org.mybatis.generator.api.MyBatisGenerator")
26     public static final SqlColumn<LocalDateTime> createTime = role.createTime;
27
28     @Generated("org.mybatis.generator.api.MyBatisGenerator")
29     public static final SqlColumn<LocalDateTime> expireTime = role.expireTime;
30
31     @Generated("org.mybatis.generator.api.MyBatisGenerator")
32     public static final SqlColumn<Boolean> due = role.due;
33
34     @Generated("org.mybatis.generator.api.MyBatisGenerator")
35     public static final class Role extends SqlTable {
36         public final SqlColumn<Integer> id = column("id", JDBCType.INTEGER);
37
38         public final SqlColumn<String> name = column("name", JDBCType.VARCHAR);
39
40         public final SqlColumn<String> authorityIds = column("authority_ids", JDBCType.VARCHAR);
41
42         public final SqlColumn<Integer> createUserId = column("create_user_id", JDBCType.INTEGER);
43
44         public final SqlColumn<LocalDateTime> createTime = column("create_time", JDBCType.TIMESTAMP);
45
46         public final SqlColumn<LocalDateTime> expireTime = column("expire_time", JDBCType.TIMESTAMP);
47
48         public final SqlColumn<Boolean> due = column("due", JDBCType.BIT);
49
50         public Role() {
51             super("role");
52         }
53     }
54 }

至此,mybatis dynamic sql代码生成成功

项目地址 https://gitee.com/hjm0928/MybatisTest

如何使用请看IDEA+SpringBoot  MyBatis Dynamic SQL的初体验(二)

    

  

  

原文地址:https://www.cnblogs.com/hjm0928/p/9955228.html

时间: 2024-10-10 02:37:03

IDEA+SpringBoot MyBatis Dynamic SQL的初体验(一)的相关文章

IDEA+SpringBoot MyBatis Dynamic SQL的初体验(二)

在上节IDEA+SpringBoot MyBatis Dynamic SQL的初体验(一)中,讲解了Mybatis Dynamic SQL数据库生成https://www.cnblogs.com/hjm0928/p/9955228.html 现在那看一下怎么使用 先看一下项目结构 可以看到实体类,Mapper文件和DynamicSqlSupport文件都生成成功了 第一步 修改application.properties修改为application.yml  内容如下 spring: datas

Oracle SQL篇(一)null值之初体验

    从我第一次正式的写sql语句到现在,已经超过10年的时间了.我写报表,做统计分析和财务对账,我一点点的接触oracle数据库,并尝试深入了解.这条路,一走就是10年,从充满热情,到开始厌倦,我不知道我还能坚持多久,未来的路,谁知道呢? 也许是该抓紧时间,做一点什么了,我不知道该开始写些什么,我从来没有在网上写东西的习惯.     先从简单的开始吧,那当然就是SQL,这是我SQL系列的第一篇,希望我能够坚持. 在Oracle数据库中,如果一个表中的列没有值的话,我们可以说是空值,比如IT员

Can I use MyBatis to generate Dynamic SQL without executing it?

Although MyBatis was designed to execute the query after it builds it, you can make use of it's configuration and a little bit of "inside knowledge" to get to what you need. MyBatis is a very nice framework, unfortunately it lacks on the documen

SpringBoot初体验及原理解析

一.前言 ? 我们来用SpringBoot开始HelloWorld之旅.SpringBoot是Spring框架对"约定大于配置(Convention over Configuration)"理念的最佳实践.SpringBoot应用本质上就是一个基于Spring框架的应用.我们大多数程序猿已经对Spring特别熟悉了,那随着我们的深入挖掘,会发现SpringBoot中并没有什么新鲜事,如果你不信,那就一起走着瞧呗! 二.SpringBoot初体验 首先,我们按照下图中的步骤生成一个Spr

springboot+支付宝完成秒杀项目的初体验

springboot+支付宝完成秒杀项目的初体验 思考的问题: 首先是秒杀的商品查询,考虑到是热点数据,所以写一个接口读取当日批次的秒杀商品到redis中(那么接下来对商品的操作都放入redis中). 当用户抢购商品时,考虑到的是是否在秒杀时间段内以及商品是抢完的问题.首先需要判断该商品是否在秒杀时间内,然后要查询该商品数量是否足够.当然这些还不够,还要有为了防止高并发的解决方案: 对用户限流:对恶意请求通过ip设置访问次数,超过次数则抛出异常. 利用消息队列的异步请求来削峰. 利用redis做

Java实战之路(1):SpringBoot项目中使用Mybatis打印Sql语句

SpringBoot项目中使用Mybatis打印Sql语句 如题,实际项目中使用很多都会用到SpringBoot+Mybatis的经典搭配进行开发,数据库里明明有数据,可是程序运行就是查不到,此时我们在本地Debug时,需要将Mybatis的实际Sql打印出来,看看Sql与我们期望的是否一致,或者将Sql拿到数据库中直接执行,看看结果.这里简单介绍几种实战中的用法. 方法一 properties:在application.properties配置文件中增加如下配置 logging.level.c

SQL SERVER FOR LINUX初体验

今天得空,就在Ubuntu17.04上安装了SQL SERVER 2017体验下,总体来说还是不错的. 在Ubuntu上安装SQL SERVER 2017还是比较方便的,只需几条命令即可: curl https://packages.microsoft.com/keys/microsoft.asc sudo add-apt-repository "$(curl https://packages.microsoft.com/config/ubuntu/16.04/mssql-server.list

Mybatis Dynamic Query 前言

初入JAVA 因为工作关系,开始接触JAVA(但心中一直割舍不下我大.net).一开始选择持久化框架的时候,同事选的是Mybatis,开始我还闹情绪,感觉应该选hibernate,因为以前用EntityFramework 感觉还不错.关键是入JAVA不久,算了就用Mybatis 吧,也算是误打误撞才有了这个动态查询框架. Mybatis 震撼 如果说hibernate是全自动的,那么Mybatis 就是半自动.Mybatis 比 hibernate 更强的在于他对sql 的控制更加好,hiber

Node.js 网页瘸腿爬虫初体验

延续上一篇,想把自己博客的文档标题利用Node.js的request全提取出来,于是有了下面的初哥爬虫,水平有限,这只爬虫目前还有点瘸腿,请看官你指正了. // 内置http模块,提供了http服务器和客户端功能 var http=require("http"); // 内置文件处理模块 var fs=require('fs'); // 创建一个将流数据写入文件的WriteStream对象 var outstream=fs.createWriteStream('./1.txt'); /