码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2018-11-13 23:56:23      阅读:1240      评论:0      收藏:0      [点我收藏+]

标签:bpa   内省   xaml   兼容   ide   from   timestamp   管理器   tar   

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>
View Code

在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);
    }
}
View Code

执行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 }
View Code

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 }
View Code

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

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

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

 

 

 

 

    

 

 

 

  

  

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

标签:bpa   内省   xaml   兼容   ide   from   timestamp   管理器   tar   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!