feat: 新增根据实体类对象,生成查询条件

This commit is contained in:
开源海哥 2023-07-19 12:44:50 +08:00 committed by dazhou
parent 9544aeebd6
commit 2e88aeea59
5 changed files with 149 additions and 49 deletions

View File

@ -24,6 +24,7 @@ import com.mybatisflex.core.dialect.DbType;
import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactory;
import javax.sql.DataSource;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -108,6 +109,10 @@ public class FlexGlobalConfig {
public void setConfiguration(Configuration configuration) { public void setConfiguration(Configuration configuration) {
this.configuration = configuration; this.configuration = configuration;
DataSource dataSource = configuration.getEnvironment().getDataSource();
if (dataSource instanceof FlexDataSource){
this.dbType = ((FlexDataSource) dataSource).getDefaultDbType();
}
} }
public SqlSessionFactory getSqlSessionFactory() { public SqlSessionFactory getSqlSessionFactory() {

View File

@ -44,13 +44,20 @@ public class FlexDataSource extends AbstractDataSource {
private final Map<String, DataSource> dataSourceMap = new HashMap<>(); private final Map<String, DataSource> dataSourceMap = new HashMap<>();
private final Map<String, DbType> dbTypeHashMap = new HashMap<>(); private final Map<String, DbType> dbTypeHashMap = new HashMap<>();
private final DbType defaultDbType;
private final String defaultDataSourceKey; private final String defaultDataSourceKey;
private final DataSource defaultDataSource; private final DataSource defaultDataSource;
public FlexDataSource(String dataSourceKey, DataSource dataSource) { public FlexDataSource(String dataSourceKey, DataSource dataSource) {
DataSourceManager.decryptDataSource(dataSource);
this.defaultDataSourceKey = dataSourceKey; this.defaultDataSourceKey = dataSourceKey;
this.defaultDataSource = dataSource; this.defaultDataSource = dataSource;
addDataSource(dataSourceKey, dataSource); this.defaultDbType = DbTypeUtil.getDbType(dataSource);
dataSourceMap.put(dataSourceKey, dataSource);
dbTypeHashMap.put(dataSourceKey, defaultDbType);
} }
public void addDataSource(String dataSourceKey, DataSource dataSource) { public void addDataSource(String dataSourceKey, DataSource dataSource) {
@ -80,10 +87,15 @@ public class FlexDataSource extends AbstractDataSource {
return defaultDataSource; return defaultDataSource;
} }
public DbType getDefaultDbType() {
return defaultDbType;
}
public DbType getDbType(String dataSourceKey) { public DbType getDbType(String dataSourceKey) {
return dbTypeHashMap.get(dataSourceKey); return dbTypeHashMap.get(dataSourceKey);
} }
@Override @Override
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
String xid = TransactionContext.getXID(); String xid = TransactionContext.getXID();

View File

@ -17,8 +17,6 @@ package com.mybatisflex.core.mybatis;
import com.mybatisflex.core.FlexConsts; import com.mybatisflex.core.FlexConsts;
import com.mybatisflex.core.FlexGlobalConfig; import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.dialect.DbType;
import com.mybatisflex.core.dialect.DbTypeUtil;
import com.mybatisflex.core.exception.FlexExceptions; import com.mybatisflex.core.exception.FlexExceptions;
import org.apache.ibatis.builder.xml.XMLConfigBuilder; import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.exceptions.ExceptionFactory; import org.apache.ibatis.exceptions.ExceptionFactory;
@ -85,10 +83,9 @@ public class FlexSqlSessionFactoryBuilder extends SqlSessionFactoryBuilder {
} }
SqlSessionFactory sessionFactory = super.build(configuration); SqlSessionFactory sessionFactory = super.build(configuration);
DbType dbType = DbTypeUtil.getDbType(configuration.getEnvironment().getDataSource());
//设置全局配置的 sessionFactory dbType // 设置全局配置的 sessionFactory
initGlobalConfig(configuration, sessionFactory, dbType); initGlobalConfig(configuration, sessionFactory);
printBanner(); printBanner();
@ -115,10 +112,9 @@ public class FlexSqlSessionFactoryBuilder extends SqlSessionFactoryBuilder {
* @param config * @param config
* @param sessionFactory * @param sessionFactory
*/ */
private void initGlobalConfig(Configuration config, SqlSessionFactory sessionFactory, DbType dbType) { private void initGlobalConfig(Configuration config, SqlSessionFactory sessionFactory) {
FlexGlobalConfig flexGlobalConfig = new FlexGlobalConfig(); FlexGlobalConfig flexGlobalConfig = new FlexGlobalConfig();
flexGlobalConfig.setSqlSessionFactory(sessionFactory); flexGlobalConfig.setSqlSessionFactory(sessionFactory);
flexGlobalConfig.setDbType(dbType);
flexGlobalConfig.setConfiguration(config); flexGlobalConfig.setConfiguration(config);
String environmentId = config.getEnvironment().getId(); String environmentId = config.getEnvironment().getId();

View File

@ -15,24 +15,95 @@
*/ */
package com.mybatisflex.core.query; package com.mybatisflex.core.query;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Consumer;
import com.mybatisflex.core.FlexConsts; import com.mybatisflex.core.FlexConsts;
import com.mybatisflex.core.constant.SqlConsts; import com.mybatisflex.core.constant.SqlConsts;
import com.mybatisflex.core.dialect.DialectFactory; import com.mybatisflex.core.dialect.DialectFactory;
import com.mybatisflex.core.table.ColumnInfo;
import com.mybatisflex.core.table.TableDef; import com.mybatisflex.core.table.TableDef;
import com.mybatisflex.core.table.TableInfo; import com.mybatisflex.core.table.TableInfo;
import com.mybatisflex.core.table.TableInfoFactory; import com.mybatisflex.core.table.TableInfoFactory;
import com.mybatisflex.core.util.*; import com.mybatisflex.core.util.*;
import java.util.*;
import java.util.function.Consumer;
public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> { public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
public static QueryWrapper create() { public static QueryWrapper create() {
return new QueryWrapper(); return new QueryWrapper();
} }
/**
* 根据实体类对象构建查询条件
* 查询出的列不包含大字段列
* @param entity 实体类对象
* @return 查询对象
*/
public static QueryWrapper create(Object entity) {
return create(entity, false);
}
/**
* 根据实体类对象构建查询条件
* @param entity 实体类对象
* @param needLargeColumn 查询出的列是否包含大字段列
* @return 查询对象
*/
public static QueryWrapper create(Object entity, boolean needLargeColumn) {
QueryWrapper queryWrapper = create();
TableInfo tableInfo = TableInfoFactory.ofEntityClass(entity.getClass());
Map<String, Object> whereMap = getWhereMap(entity);
String[] selectColumn = needLargeColumn ? tableInfo.getAllColumns() : tableInfo.getDefaultQueryColumns();
queryWrapper.select(selectColumn);
queryWrapper.where(whereMap);
return queryWrapper;
}
/**
* 根据实体类对象获取查询条件的参数
* @param entity 实体类对象
* @return key实体对象的字段对应的列名称value 字段值
*/
public static Map<String, Object> getWhereMap(Object entity) {
Class<?> entityClass = entity.getClass();
TableInfo tableInfo = TableInfoFactory.ofEntityClass(entity.getClass());
Map<String, Object> dataMap = new HashMap<>();
// 添加非主键列
for (ColumnInfo columnInfo : tableInfo.getColumnInfoList()) {
// 跳过逻辑删除列
if (columnInfo.getColumn().equals(tableInfo.getLogicDeleteColumn())) {
continue;
}
try {
Field declaredField = entityClass.getDeclaredField(columnInfo.getProperty());
declaredField.setAccessible(true);
Object value = declaredField.get(entity);
if (Objects.isNull(value)) {
continue;
}
dataMap.put(columnInfo.getColumn(), value);
} catch (Exception e) {
e.printStackTrace();
}
}
// 添加主键列
for (ColumnInfo columnInfo : tableInfo.getPrimaryKeyList()) {
try {
Field declaredField = entityClass.getDeclaredField(columnInfo.getProperty());
declaredField.setAccessible(true);
Object value = declaredField.get(entity);
if (Objects.isNull(value)) {
continue;
}
dataMap.put(columnInfo.getColumn(), value);
} catch (Exception e) {
e.printStackTrace();
}
}
return dataMap;
}
public WithBuilder with(String name) { public WithBuilder with(String name) {
if (with == null) { if (with == null) {
@ -62,12 +133,10 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return new WithBuilder(this, with, name, Arrays.asList(params)); return new WithBuilder(this, with, name, Arrays.asList(params));
} }
public QueryWrapper select() { public QueryWrapper select() {
return this; return this;
} }
public QueryWrapper select(String... columns) { public QueryWrapper select(String... columns) {
for (String column : columns) { for (String column : columns) {
addSelectColumn(new StringQueryColumn(column)); addSelectColumn(new StringQueryColumn(column));
@ -75,7 +144,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public <T> QueryWrapper select(LambdaGetter<T>... lambdaGetters) { public <T> QueryWrapper select(LambdaGetter<T>... lambdaGetters) {
for (LambdaGetter<T> lambdaGetter : lambdaGetters) { for (LambdaGetter<T> lambdaGetter : lambdaGetters) {
QueryColumn queryColumn = LambdaUtil.getQueryColumn(lambdaGetter); QueryColumn queryColumn = LambdaUtil.getQueryColumn(lambdaGetter);
@ -84,7 +152,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper select(QueryColumn... queryColumns) { public QueryWrapper select(QueryColumn... queryColumns) {
for (QueryColumn column : queryColumns) { for (QueryColumn column : queryColumns) {
if (column != null) { if (column != null) {
@ -107,7 +174,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper from(TableDef... tableDefs) { public QueryWrapper from(TableDef... tableDefs) {
for (TableDef tableDef : tableDefs) { for (TableDef tableDef : tableDefs) {
from(new QueryTable(tableDef)); from(new QueryTable(tableDef));
@ -115,7 +181,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper from(Class<?>... entityClasses) { public QueryWrapper from(Class<?>... entityClasses) {
for (Class<?> entityClass : entityClasses) { for (Class<?> entityClass : entityClasses) {
TableInfo tableInfo = TableInfoFactory.ofEntityClass(entityClass); TableInfo tableInfo = TableInfoFactory.ofEntityClass(entityClass);
@ -124,7 +189,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper from(String... tables) { public QueryWrapper from(String... tables) {
for (String table : tables) { for (String table : tables) {
if (StringUtil.isBlank(table)) { if (StringUtil.isBlank(table)) {
@ -142,7 +206,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper from(QueryTable... tables) { public QueryWrapper from(QueryTable... tables) {
if (CollectionUtil.isEmpty(queryTables)) { if (CollectionUtil.isEmpty(queryTables)) {
queryTables = new ArrayList<>(); queryTables = new ArrayList<>();
@ -163,12 +226,10 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper from(QueryWrapper queryWrapper) { public QueryWrapper from(QueryWrapper queryWrapper) {
return from(new SelectQueryTable(queryWrapper)); return from(new SelectQueryTable(queryWrapper));
} }
public QueryWrapper as(String alias) { public QueryWrapper as(String alias) {
if (CollectionUtil.isEmpty(queryTables)) { if (CollectionUtil.isEmpty(queryTables)) {
throw new IllegalArgumentException("query table must not be empty."); throw new IllegalArgumentException("query table must not be empty.");
@ -178,7 +239,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper where(QueryCondition queryCondition) { public QueryWrapper where(QueryCondition queryCondition) {
this.setWhereQueryCondition(queryCondition); this.setWhereQueryCondition(queryCondition);
return this; return this;
@ -189,13 +249,11 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper where(String sql, Object... params) { public QueryWrapper where(String sql, Object... params) {
this.setWhereQueryCondition(new RawFragment(sql, params)); this.setWhereQueryCondition(new RawFragment(sql, params));
return this; return this;
} }
public QueryWrapper where(Map<String, Object> whereConditions) { public QueryWrapper where(Map<String, Object> whereConditions) {
if (whereConditions != null) { if (whereConditions != null) {
whereConditions.forEach((s, o) -> and(QueryCondition.create(new QueryColumn(s), o))); whereConditions.forEach((s, o) -> and(QueryCondition.create(new QueryColumn(s), o)));
@ -225,7 +283,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return new QueryConditionBuilder(this, LambdaUtil.getQueryColumn(fn), SqlConnector.AND); return new QueryConditionBuilder(this, LambdaUtil.getQueryColumn(fn), SqlConnector.AND);
} }
public QueryWrapper and(Consumer<QueryWrapper> consumer) { public QueryWrapper and(Consumer<QueryWrapper> consumer) {
QueryWrapper newWrapper = new QueryWrapper(); QueryWrapper newWrapper = new QueryWrapper();
consumer.accept(newWrapper); consumer.accept(newWrapper);
@ -268,7 +325,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.LEFT_JOIN, new QueryTable(table), true); return joining(SqlConsts.LEFT_JOIN, new QueryTable(table), true);
} }
public Joiner<QueryWrapper> leftJoin(String table, boolean when) { public Joiner<QueryWrapper> leftJoin(String table, boolean when) {
return joining(SqlConsts.LEFT_JOIN, new QueryTable(table), when); return joining(SqlConsts.LEFT_JOIN, new QueryTable(table), when);
} }
@ -297,7 +353,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.LEFT_JOIN, table, when); return joining(SqlConsts.LEFT_JOIN, table, when);
} }
public Joiner<QueryWrapper> rightJoin(String table) { public Joiner<QueryWrapper> rightJoin(String table) {
return joining(SqlConsts.RIGHT_JOIN, new QueryTable(table), true); return joining(SqlConsts.RIGHT_JOIN, new QueryTable(table), true);
} }
@ -330,7 +385,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.RIGHT_JOIN, table, when); return joining(SqlConsts.RIGHT_JOIN, table, when);
} }
public Joiner<QueryWrapper> innerJoin(String table) { public Joiner<QueryWrapper> innerJoin(String table) {
return joining(SqlConsts.INNER_JOIN, new QueryTable(table), true); return joining(SqlConsts.INNER_JOIN, new QueryTable(table), true);
} }
@ -363,7 +417,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.INNER_JOIN, table, when); return joining(SqlConsts.INNER_JOIN, table, when);
} }
public Joiner<QueryWrapper> fullJoin(String table) { public Joiner<QueryWrapper> fullJoin(String table) {
return joining(SqlConsts.FULL_JOIN, new QueryTable(table), true); return joining(SqlConsts.FULL_JOIN, new QueryTable(table), true);
} }
@ -396,7 +449,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.FULL_JOIN, table, when); return joining(SqlConsts.FULL_JOIN, table, when);
} }
public Joiner<QueryWrapper> crossJoin(String table) { public Joiner<QueryWrapper> crossJoin(String table) {
return joining(SqlConsts.CROSS_JOIN, new QueryTable(table), true); return joining(SqlConsts.CROSS_JOIN, new QueryTable(table), true);
} }
@ -429,7 +481,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.CROSS_JOIN, table, when); return joining(SqlConsts.CROSS_JOIN, table, when);
} }
public Joiner<QueryWrapper> join(String table) { public Joiner<QueryWrapper> join(String table) {
return joining(SqlConsts.JOIN, new QueryTable(table), true); return joining(SqlConsts.JOIN, new QueryTable(table), true);
} }
@ -462,7 +513,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return joining(SqlConsts.JOIN, table, when); return joining(SqlConsts.JOIN, table, when);
} }
public QueryWrapper union(QueryWrapper unionQuery) { public QueryWrapper union(QueryWrapper unionQuery) {
if (unions == null) { if (unions == null) {
unions = new ArrayList<>(); unions = new ArrayList<>();
@ -489,12 +539,10 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
// public QueryWrapper end(String sqlPart){
// public QueryWrapper end(String sqlPart){ // addEndFragment(sqlPart);
// addEndFragment(sqlPart); // return this;
// return this; // }
// }
protected Joiner<QueryWrapper> joining(String type, QueryTable table, boolean when) { protected Joiner<QueryWrapper> joining(String type, QueryTable table, boolean when) {
Join join = new Join(type, table, when); Join join = new Join(type, table, when);
@ -514,7 +562,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return new Joiner<>(addJoin(join), join); return new Joiner<>(addJoin(join), join);
} }
public QueryWrapper groupBy(String name) { public QueryWrapper groupBy(String name) {
addGroupByColumns(new QueryColumn(name)); addGroupByColumns(new QueryColumn(name));
return this; return this;
@ -539,7 +586,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper having(QueryCondition queryCondition) { public QueryWrapper having(QueryCondition queryCondition) {
addHavingQueryCondition(queryCondition, SqlConnector.AND); addHavingQueryCondition(queryCondition, SqlConnector.AND);
return this; return this;
@ -565,7 +611,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return this; return this;
} }
public QueryWrapper limit(Integer rows) { public QueryWrapper limit(Integer rows) {
setLimitRows(rows); setLimitRows(rows);
return this; return this;
@ -687,7 +732,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return returnValues; return returnValues;
} }
List<QueryWrapper> getChildSelect() { List<QueryWrapper> getChildSelect() {
List<QueryWrapper> tableChildQuery = null; List<QueryWrapper> tableChildQuery = null;
@ -703,7 +747,6 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
} }
} }
List<QueryWrapper> whereChildQuery = WrapperUtil.getChildQueryWrapper(whereQueryCondition); List<QueryWrapper> whereChildQuery = WrapperUtil.getChildQueryWrapper(whereQueryCondition);
List<QueryWrapper> havingChildQuery = WrapperUtil.getChildQueryWrapper(havingQueryCondition); List<QueryWrapper> havingChildQuery = WrapperUtil.getChildQueryWrapper(havingQueryCondition);
@ -711,22 +754,19 @@ public class QueryWrapper extends BaseQueryWrapper<QueryWrapper> {
return Collections.emptyList(); return Collections.emptyList();
} }
List<QueryWrapper> childQueryWrappers = tableChildQuery == null ? new ArrayList<>()
List<QueryWrapper> childQueryWrappers = tableChildQuery == null : new ArrayList<>(tableChildQuery);
? new ArrayList<>() : new ArrayList<>(tableChildQuery);
childQueryWrappers.addAll(whereChildQuery); childQueryWrappers.addAll(whereChildQuery);
childQueryWrappers.addAll(havingChildQuery); childQueryWrappers.addAll(havingChildQuery);
return childQueryWrappers; return childQueryWrappers;
} }
public String toSQL() { public String toSQL() {
String sql = DialectFactory.getDialect().forSelectByQuery(this); String sql = DialectFactory.getDialect().forSelectByQuery(this);
return SqlUtil.replaceSqlParams(sql, getValueArray()); return SqlUtil.replaceSqlParams(sql, getValueArray());
} }
@Override @Override
public QueryWrapper clone() { public QueryWrapper clone() {
return super.clone(); return super.clone();

View File

@ -0,0 +1,47 @@
package com.mybatisflex.test;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import com.mybatisflex.core.MybatisFlexBootstrap;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.core.audit.ConsoleMessageCollector;
import com.mybatisflex.core.audit.MessageCollector;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.mapper.Entity04Mapper;
public class QueryWrapperTest {
public static void main(String[] args) {
DataSource dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("schema04.sql")
.addScript("data04.sql").build();
MybatisFlexBootstrap bootstrap = MybatisFlexBootstrap.getInstance().setDataSource(dataSource)
.addMapper(Entity04Mapper.class).start();
//开启审计功能
AuditManager.setAuditEnable(true);
//设置 SQL 审计收集器
MessageCollector collector = new ConsoleMessageCollector();
AuditManager.setMessageCollector(collector);
Entity04Mapper mapper = bootstrap.getMapper(Entity04Mapper.class);
Entity04 entity04 = new Entity04();
entity04.setId("1");
entity04.setAge(200);
mapper.insertSelective(entity04);
System.out.println("--------------------selectListByQuery");
QueryWrapper queryWrapper = QueryWrapper.create(entity04);
List<Entity04> entity04s = mapper.selectListByQuery(queryWrapper);
System.out.println(entity04s);
}
}