AutoSqlInjector.java 23.4 KB
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
/**
* Copyright (c) 2011-2014, hubin (jobob@qq.com).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.baomidou.mybatisplus.mapper;

import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.entity.TableFieldInfo;
import com.baomidou.mybatisplus.entity.TableInfo;
import com.baomidou.mybatisplus.enums.DBType;
import com.baomidou.mybatisplus.enums.FieldStrategy;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.enums.SqlMethod;
import com.baomidou.mybatisplus.toolkit.SqlReservedWords;
import com.baomidou.mybatisplus.toolkit.TableInfoHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
* <p>
* SQL 自动注入器
* </p>
*
* @author hubin sjy
* @Date 2016-09-09
*/
public class AutoSqlInjector implements ISqlInjector {

private static final Log logger = LogFactory.getLog(AutoSqlInjector.class);

protected Configuration configuration;

protected LanguageDriver languageDriver;

protected MapperBuilderAssistant builderAssistant;

protected DBType dbType = DBType.MYSQL;

/**
* CRUD注入后给予标识 注入过后不再注入
*
* @param builderAssistant
* @param mapperClass
*/
public void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
String className = mapperClass.toString();
Set<String> mapperRegistryCache = GlobalConfiguration.getMapperRegistryCache(builderAssistant.getConfiguration());
if (!mapperRegistryCache.contains(className)) {
inject(builderAssistant, mapperClass);
mapperRegistryCache.add(className);
}
}

/**
* 注入单点 crudSql
*/
public void inject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass) {
this.configuration = builderAssistant.getConfiguration();
this.builderAssistant = builderAssistant;
this.languageDriver = configuration.getDefaultScriptingLanuageInstance();
GlobalConfiguration globalCache = GlobalConfiguration.GlobalConfig(configuration);
this.dbType = globalCache.getDbType();
/*
* 驼峰设置 PLUS 配置 > 原始配置
*/
if (!globalCache.isDbColumnUnderline()) {
globalCache.setDbColumnUnderline(configuration.isMapUnderscoreToCamelCase());
}
Class<?> modelClass = extractModelClass(mapperClass);
TableInfo table = TableInfoHelper.initTableInfo(builderAssistant, modelClass);

/**
* 没有指定主键,默认方法不能使用
*/
if (null != table && null != table.getKeyProperty()) {
/* 插入 */
this.injectInsertOneSql(mapperClass, modelClass, table);

/* 删除 */
this.injectDeleteSql(mapperClass, modelClass, table);
this.injectDeleteByMapSql(mapperClass, table);
this.injectDeleteByIdSql(false, mapperClass, modelClass, table);
this.injectDeleteByIdSql(true, mapperClass, modelClass, table);

/* 修改 */
this.injectUpdateByIdSql(mapperClass, modelClass, table);
this.injectUpdateSql(mapperClass, modelClass, table);

/* 查询 */
this.injectSelectByIdSql(false, mapperClass, modelClass, table);
this.injectSelectByIdSql(true, mapperClass, modelClass, table);
this.injectSelectByMapSql(mapperClass, modelClass, table);
this.injectSelectOneSql(mapperClass, modelClass, table);
this.injectSelectCountSql(mapperClass, modelClass, table);
this.injectSelectListSql(SqlMethod.SELECT_LIST, mapperClass, modelClass, table);
this.injectSelectListSql(SqlMethod.SELECT_PAGE, mapperClass, modelClass, table);

/* 自定义方法 */
this.inject(configuration, builderAssistant, mapperClass, modelClass, table);
} else {
/**
* 警告
*/
logger.warn(String.format("%s ,Not found @TableId annotation, cannot use mybatis-plus curd method.",
modelClass.toString()));
}
}

/**
* 自定义方法,注入点(子类需重写该方法)
*/
public void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class<?> mapperClass,
Class<?> modelClass, TableInfo table) {
// to do nothing
}

protected Class<?> extractModelClass(Class<?> mapperClass) {
Type[] types = mapperClass.getGenericInterfaces();
ParameterizedType target = null;
for (Type type : types) {
if (type instanceof ParameterizedType && BaseMapper.class.isAssignableFrom(mapperClass)) {
target = (ParameterizedType) type;
break;
}
}
Type[] parameters = target.getActualTypeArguments();
Class<?> modelClass = (Class<?>) parameters[0];
return modelClass;
}

/**
* <p>
* 注入插入 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectInsertOneSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
/*
* INSERT INTO table <trim prefix="(" suffix=")" suffixOverrides=",">
* <if test="xx != null">xx,</if> </trim> <trim prefix="values ("
* suffix=")" suffixOverrides=","> <if test="xx != null">#{xx},</if>
* </trim>
*/
KeyGenerator keyGenerator = new NoKeyGenerator();
StringBuilder fieldBuilder = new StringBuilder();
StringBuilder placeholderBuilder = new StringBuilder();
fieldBuilder.append("\n<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n");
placeholderBuilder.append("\n<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">\n");
String keyProperty = null;
String keyColumn = null;
if (table.getIdType() == IdType.AUTO) {
/* 自增主键 */
keyGenerator = new Jdbc3KeyGenerator();
keyProperty = table.getKeyProperty();
keyColumn = table.getKeyColumn();
} else {
/* 用户输入自定义ID */
fieldBuilder.append(table.getKeyColumn()).append(",");
placeholderBuilder.append("#{").append(table.getKeyProperty()).append("},");
}
List<TableFieldInfo> fieldList = table.getFieldList();
for (TableFieldInfo fieldInfo : fieldList) {
fieldBuilder.append(convertIfTagIgnored(fieldInfo, false));
fieldBuilder.append(fieldInfo.getColumn()).append(",");
fieldBuilder.append(convertIfTagIgnored(fieldInfo, true));
placeholderBuilder.append(convertIfTagIgnored(fieldInfo, false));
placeholderBuilder.append("#{").append(fieldInfo.getEl()).append("},");
placeholderBuilder.append(convertIfTagIgnored(fieldInfo, true));
}
fieldBuilder.append("\n</trim>");
placeholderBuilder.append("\n</trim>");
SqlMethod sqlMethod = SqlMethod.INSERT_ONE;
String sql = String.format(sqlMethod.getSql(), table.getTableName(), fieldBuilder.toString(),
placeholderBuilder.toString());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addInsertMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource, keyGenerator, keyProperty,
keyColumn);
}

/**
* <p>
* 注入 entity 条件删除 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectDeleteSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.DELETE;
String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlWhereEntityWrapper(table));
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addDeleteMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource);
}

/**
* <p>
* 注入 map 条件删除 SQL 语句
* </p>
*
* @param mapperClass
* @param table
*/
protected void injectDeleteByMapSql(Class<?> mapperClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.DELETE_BY_MAP;
String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlWhereByMap());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);
this.addDeleteMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource);
}

/**
* <p>
* 注入删除 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectDeleteByIdSql(boolean batch, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.DELETE_BY_ID;
SqlSource sqlSource = null;
if (batch) {
sqlMethod = SqlMethod.DELETE_BATCH_BY_IDS;
StringBuilder ids = new StringBuilder();
ids.append("\n<foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">");
ids.append("#{item}");
ids.append("\n</foreach>");
String sql = String.format(sqlMethod.getSql(), table.getTableName(), table.getKeyColumn(), ids.toString());
sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
} else {
String sql = String.format(sqlMethod.getSql(), table.getTableName(), table.getKeyColumn(), table.getKeyColumn());
sqlSource = new RawSqlSource(configuration, sql, Object.class);
}
this.addDeleteMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource);
}

/**
* <p>
* 注入更新 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectUpdateByIdSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.UPDATE_BY_ID;
String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlSet(table, null), table.getKeyColumn(),
table.getKeyProperty());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}

/**
* <p>
* 注入批量更新 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectUpdateSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.UPDATE;
String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlSet(table, "et."), sqlWhereEntityWrapper(table));
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}

/**
* <p>
* 注入查询 SQL 语句
* </p>
*
* @param batch
* 是否为批量插入
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectSelectByIdSql(boolean batch, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.SELECT_BY_ID;
SqlSource sqlSource = null;
if (batch) {
sqlMethod = SqlMethod.SELECT_BATCH_BY_IDS;
StringBuilder ids = new StringBuilder();
ids.append("\n<foreach item=\"item\" index=\"index\" collection=\"list\" separator=\",\">");
ids.append("#{item}");
ids.append("\n</foreach>");
sqlSource = languageDriver.createSqlSource(configuration, String.format(sqlMethod.getSql(),
sqlSelectColumns(table, false), table.getTableName(), table.getKeyColumn(), ids.toString()), modelClass);
} else {
sqlSource = new RawSqlSource(configuration, String.format(sqlMethod.getSql(), sqlSelectColumns(table, false),
table.getTableName(), table.getKeyColumn(), table.getKeyProperty()), Object.class);
}
this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, modelClass, table);
}

/**
* <p>
* 注入 map 查询 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectSelectByMapSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.SELECT_BY_MAP;
String sql = String.format(sqlMethod.getSql(), sqlSelectColumns(table, false), table.getTableName(), sqlWhereByMap());
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Map.class);
this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, modelClass, table);
}

/**
* <p>
* 注入实体查询一条记录 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectSelectOneSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.SELECT_ONE;
String sql = String.format(sqlMethod.getSql(), sqlSelectColumns(table, false), table.getTableName(),
sqlWhere(table, false));
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, modelClass, table);
}

/**
* <p>
* 注入EntityWrapper方式查询记录列表 SQL 语句
* </p>
*
* @param sqlMethod
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectSelectListSql(SqlMethod sqlMethod, Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
String sql = String.format(sqlMethod.getSql(), sqlSelectColumns(table, true), table.getTableName(),
sqlWhereEntityWrapper(table));
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, modelClass, table);
}

/**
* <p>
* 注入EntityWrapper查询总记录数 SQL 语句
* </p>
*
* @param mapperClass
* @param modelClass
* @param table
*/
protected void injectSelectCountSql(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {
SqlMethod sqlMethod = SqlMethod.SELECT_COUNT;
String sql = String.format(sqlMethod.getSql(), table.getTableName(), sqlWhereEntityWrapper(table));
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
this.addSelectMappedStatement(mapperClass, sqlMethod.getMethod(), sqlSource, Integer.class, null);
}

/**
* <p>
* EntityWrapper方式获取select where
* </p>
*
* @param table
* @return String
*/
protected String sqlWhereEntityWrapper(TableInfo table) {
StringBuilder where = new StringBuilder("\n<if test=\"ew!=null\">");
where.append("\n<if test=\"ew.entity!=null\">\n<where>");
where.append("\n<if test=\"ew.entity.").append(table.getKeyProperty()).append("!=null\">\n");
where.append(table.getKeyColumn()).append("=#{ew.entity.").append(table.getKeyProperty()).append("}");
where.append("\n</if>");
List<TableFieldInfo> fieldList = table.getFieldList();
for (TableFieldInfo fieldInfo : fieldList) {
where.append(convertIfTag(fieldInfo, "ew.entity.", false));
where.append(" AND ").append(fieldInfo.getColumn()).append("=#{ew.entity.").append(fieldInfo.getEl()).append("}");
where.append(convertIfTag(fieldInfo, true));
}
where.append("\n</where>\n</if>");
where.append("\n<if test=\"ew.sqlSegment!=null\">\n${ew.sqlSegment}\n</if>");
where.append("\n</if>");
return where.toString();
}

/**
* <p>
* SQL 更新 set 语句
* </p>
*
* @param table
* @param prefix
* 前缀
* @return
*/
protected String sqlSet(TableInfo table, String prefix) {
StringBuilder set = new StringBuilder();
set.append("<trim prefix=\"SET\" suffixOverrides=\",\">");
List<TableFieldInfo> fieldList = table.getFieldList();
for (TableFieldInfo fieldInfo : fieldList) {
set.append(convertIfTag(true, fieldInfo, prefix, false));
set.append(fieldInfo.getColumn()).append("=#{");
if (null != prefix) {
set.append(prefix);
}
set.append(fieldInfo.getEl()).append("},");
set.append(convertIfTag(true, fieldInfo, null, true));
}
set.append("\n</trim>");
return set.toString();
}

/**
* <p>
* 获取需要转义的SQL字段
* </p>
*
* @param convertStr
* @return
*/
protected String sqlWordConvert(String convertStr) {
DBType dbType = GlobalConfiguration.getDbType(configuration);
return SqlReservedWords.convert(dbType, convertStr);
}

/**
* <p>
* SQL 查询所有表字段
* </p>
*
* @param table
* @param entityWrapper
* 是否为包装类型查询
* @return
*/
protected String sqlSelectColumns(TableInfo table, boolean entityWrapper) {
StringBuilder columns = new StringBuilder();
if (null != table.getResultMap()) {
/*
* 存在 resultMap 映射返回
*/
if (entityWrapper) {
columns.append("<choose><when test=\"ew != null and ew.sqlSelect != null\">${ew.sqlSelect}</when><otherwise>");
}
columns.append("*");
if (entityWrapper) {
columns.append("</otherwise></choose>");
}
} else {
/*
* 普通查询
*/
if (entityWrapper) {
columns.append("<choose><when test=\"ew != null and ew.sqlSelect != null\">${ew.sqlSelect}</when><otherwise>");
}
if (table.isKeyRelated()) {
columns.append(table.getKeyColumn()).append(" AS ").append(sqlWordConvert(table.getKeyProperty()));
} else {
columns.append(sqlWordConvert(table.getKeyProperty()));
}
List<TableFieldInfo> fieldList = table.getFieldList();
for (TableFieldInfo fieldInfo : fieldList) {
columns.append(",").append(fieldInfo.getColumn());
if (fieldInfo.isRelated()) {
columns.append(" AS ").append(sqlWordConvert(fieldInfo.getProperty()));
}
}
if (entityWrapper) {
columns.append("</otherwise></choose>");
}
}

/*
* 返回所有查询字段内容
*/
return columns.toString();
}

/**
* <p>
* SQL 查询条件
* </p>
*
* @param table
* @param space
* 是否为空判断
* @return
*/
protected String sqlWhere(TableInfo table, boolean space) {
StringBuilder where = new StringBuilder();
if (space) {
where.append("\n<if test=\"ew!=null\">");
}
where.append("\n<where>");
where.append("\n<if test=\"ew.").append(table.getKeyProperty()).append("!=null\">\n");
where.append(table.getKeyColumn()).append("=#{ew.").append(table.getKeyProperty()).append("}");
where.append("\n</if>");
List<TableFieldInfo> fieldList = table.getFieldList();
for (TableFieldInfo fieldInfo : fieldList) {
where.append(convertIfTag(fieldInfo, "ew.", false));
where.append(" AND ").append(fieldInfo.getColumn()).append("=#{ew.").append(fieldInfo.getEl()).append("}");
where.append(convertIfTag(fieldInfo, true));
}
where.append("\n</where>");
if (space) {
where.append("\n</if>");
}
return where.toString();
}

/**
* <p>
* SQL map 查询条件
* </p>
*/
protected String sqlWhereByMap() {
StringBuilder where = new StringBuilder();
where.append("\n<if test=\"cm!=null and !cm.isEmpty\">");
where.append("\n<where>");
where.append("\n<foreach collection=\"cm.keys\" item=\"k\" separator=\"AND\">");
where.append("\n<if test=\"cm[k] != null\">");
if (DBType.MYSQL.equals(dbType)) {
where.append("\n`${k}` = #{cm[${k}]}");
} else {
where.append("\n${k} = #{cm[${k}]}");
}
where.append("\n</if>");
where.append("\n</foreach>");
where.append("\n</where>");
where.append("\n</if>");
return where.toString();
}

/**
* <p>
* IF 条件转换方法
* </p>
*
* @param ignored
* 允许忽略
* @param fieldInfo
* 字段信息
* @param prefix
* 条件前缀
* @param colse
* 是否闭合标签
* @return
*/
protected String convertIfTag(boolean ignored, TableFieldInfo fieldInfo, String prefix, boolean colse) {
/* 忽略策略 */
FieldStrategy fieldStrategy = fieldInfo.getFieldStrategy();
if (fieldStrategy == FieldStrategy.IGNORED) {
if (ignored) {
return "";
}
//TODO 考虑日期类型忽略
// 查询策略,使用全局策略
fieldStrategy = GlobalConfiguration.GlobalConfig(configuration).getFieldStrategy();
}

// 关闭标签
if (colse) {
return "</if>";
}

/* 前缀处理 */
String property = fieldInfo.getProperty();
if (null != prefix) {
property = prefix + property;
}

// 验证逻辑
if (fieldStrategy == FieldStrategy.NOT_EMPTY) {
return String.format("\n\t<if test=\"%s!=null and %s!=''\">", property, property);
} else {
// FieldStrategy.NOT_NULL
return String.format("\n\t<if test=\"%s!=null\">", property);
}
}

protected String convertIfTagIgnored(TableFieldInfo fieldInfo, boolean colse) {
return convertIfTag(true, fieldInfo, null, colse);
}

protected String convertIfTag(TableFieldInfo fieldInfo, String prefix, boolean colse) {
return convertIfTag(false, fieldInfo, prefix, colse);
}

protected String convertIfTag(TableFieldInfo fieldInfo, boolean colse) {
return convertIfTag(fieldInfo, null, colse);
}

/*
* 查询
*/
public MappedStatement addSelectMappedStatement(Class<?> mapperClass, String id, SqlSource sqlSource, Class<?> resultType,
TableInfo table) {
if (null != table) {
String resultMap = table.getResultMap();
if (null != resultMap) {
/* 返回 resultMap 映射结果集 */
return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.SELECT, null, resultMap, null,
new NoKeyGenerator(), null, null);
}
}

/* 普通查询 */
return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.SELECT, null, null, resultType,
new NoKeyGenerator(), null, null);
}

/*
* 插入
*/
public MappedStatement addInsertMappedStatement(Class<?> mapperClass, Class<?> modelClass, String id, SqlSource sqlSource,
KeyGenerator keyGenerator, String keyProperty, String keyColumn) {
return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.INSERT, modelClass, null, Integer.class,
keyGenerator, keyProperty, keyColumn);
}

/*
* 删除
*/
public MappedStatement addDeleteMappedStatement(Class<?> mapperClass, String id, SqlSource sqlSource) {
return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.DELETE, null, null, Integer.class,
new NoKeyGenerator(), null, null);
}

/*
* 更新
*/
public MappedStatement addUpdateMappedStatement(Class<?> mapperClass, Class<?> modelClass, String id, SqlSource sqlSource) {
return this.addMappedStatement(mapperClass, id, sqlSource, SqlCommandType.UPDATE, modelClass, null, Integer.class,
new NoKeyGenerator(), null, null);
}

public MappedStatement addMappedStatement(Class<?> mapperClass, String id, SqlSource sqlSource,
SqlCommandType sqlCommandType, Class<?> parameterClass, String resultMap, Class<?> resultType,
KeyGenerator keyGenerator, String keyProperty, String keyColumn) {
String statementName = mapperClass.getName() + "." + id;
if (configuration.hasStatement(statementName)) {
System.err.println("{" + statementName
+ "} Has been loaded by XML or SqlProvider, ignoring the injection of the SQL.");
return null;
}
/* 缓存逻辑处理 */
boolean isSelect = false;
if (sqlCommandType == SqlCommandType.SELECT) {
isSelect = true;
}
return builderAssistant.addMappedStatement(id, sqlSource, StatementType.PREPARED, sqlCommandType, null, null, null,
parameterClass, resultMap, resultType, null, !isSelect, isSelect, false, keyGenerator, keyProperty, keyColumn,
configuration.getDatabaseId(), languageDriver, null);
}

}