package com.vci.starter.web.wrapper;
import com.vci.starter.web.annotation.*;
import com.vci.starter.web.constant.FrameWorkLcStatusConstant;
import com.vci.starter.web.constant.QueryOptionConstant;
import com.vci.starter.web.enumpck.DataBaseEnum;
import com.vci.starter.web.enumpck.VciFieldTypeEnum;
import com.vci.starter.web.exception.VciBaseException;
import com.vci.starter.web.pagemodel.PageHelper;
import com.vci.starter.web.pagemodel.TreeQueryObject;
import com.vci.starter.web.service.VciSecretServiceI;
import com.vci.starter.web.toolmodel.DateConverter;
import com.vci.starter.web.util.VciBaseUtil;
import com.vci.starter.web.util.VciDateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;
/**
* 查询封装
* 在mybatis的xml内容中需要写入
* ${qw.getSelectFieldSql} from XXX ${wq.getTableNick} ${qw.getLinkTableSql} ${qw.whereSql} ${qw.getPageSql}
* 特别注意,in条件后的内容不能超过1000,因为受oracle的限制
* @author weidy
* @date 2019/10/15 16:31
*/
public class VciQueryWrapperForDO implements VciSecretServiceI{
/**
* 是否用户角色部门等表格的兼容性
*/
public static boolean USER_TABLE_COMPATIBILITY = false;
/**
* 数据库的平台
*/
public static String DATABASE_PLATFORM = DataBaseEnum.ORACLE.getValue();
/**
* 在兼容老旧的平台的时候,新平台的业务类型和在老平台的数据库表的映射,key是新的平台的业务对象,value老平台中的表格,key必须是小写
*/
public static Map USER_TABLE_COMPATIBILITY_BTM_MAP = new HashMap<>();
/**
* 在兼容老旧的平台的时候,新平台的业务类型中的字段与老平台的数据库表中字段的映射,相同的时候不用添加,key是新的平台的业务对象+分隔符+字段名称,value是老平台中的表格里的字段,key全是小写
*/
public static Map USER_TABLE_COMPATIBILITY_FIELD_MAP = new HashMap<>();
/**
* 兼容老旧的平台的分隔符
*/
public static final String USER_TABLE_COMPATIBILITY_FIELD_SEP = "${vcicomplibitysep}";
/**
* 查询条件
*/
private Map conditionMap ;
/**
* 自写的SQL,可以是标识符,用于移除的时候,值是具体的sql,也可以用OR开头表示或的情况
*/
private Map customerSqlMap;
/**
* 主键的属性
*/
private String oidFieldName = "oid";
/**
* 空格
*/
private static final String SPACE = " ";
/**
* 查询密级
*/
public static final String QUERY_FIELD_SECRET = "${vciQuerySecret}";
/**
* 默认查询密级
*/
public static final Boolean DEFAULT_QUERY_SECRET = true;
/**
* 默认不查询数据权限
*/
public static final Boolean DEFAULT_QUERY_DATARIGHT = false;
/**
* 查询数据权限
*/
public static final String QUERY_FIELD_DATARIGHT = "${vciQueryDataRight}";
/**
* 查询配置
*/
private VciQueryWrapperOption queryWrapperOption ;
/**
* 数据对象
*/
private Class> doClass;
/**
* 分页对象,包含分页和排序
*/
private PageHelper pageHelper;
/**
* 所有的字段名称,key是数据库里的字段,value是对象属性中的字段
*/
private Map allFieldNameMap;
/**
* xml的field
*/
private List xmlTypeFieldList = new ArrayList<>();
/**
* 是否唯一
*/
private boolean distinct = false;
/**
* 版本管理相关的字段和显示名称映射
*/
public static final Map REVISION_MANAGE_FIELD_MAP = new HashMap(){{
put("nameoid","对象主键");
put("revisionoid","版本主键");
put("lastr","是否最新版本");
put("firstr","是否最老版本");
put("lastv","是否最新版次");
put("firstv","是否最老版次");
put("revisionrule","版本规则");
put("revisionseq","版本排序号");
put("revisionvalue","版本值");
put("versionrule","版次规则");
put("versionseq","版次排序号");
put("versionvalue","版次值");
put("checkinby","签入人");
put("checkintime","签入时间");
put("checkoutby","签出人");
put("checkouttime","签出时间");
put("copyfromversion","拷贝版本来源");
}} ;
/**
* 基础的属性字段数组
*/
public static final Map BASIC_FIELD_MAP = new HashMap(){{
put("oid","主键");
put("btmname","业务类型的名称");
put("id","编号");
put("name","名称");
put("description","描述");
put("creator","创建人");
put("createtime","创建时间");
put("lastmodifier","最后时间人");
put("lastmodifytime","最后修改时间");
put("ts","时间戳");
put("owner","拥有者");
}};
/**
* 兼容的时候,基础模型的属性映射
*/
public static final Map BASE_MODEL_COMPATIBILITY_MAP = new HashMap(){{
put("lastr","islastr");
put("firstr","isfirstr");
put("lastv","islastv");
put("firstv","isfirstv");
}};
/**
* BaseModel和BusinessObject中的属性映射。
* key:为BaseModel中的属性,value:为BusinessObject中的属性
*/
public static final Map BASEMODEL_CBO_FIELD_MAP = new HashMap(){{
put("oid", "oid");
put("revisionoid","revoid");
put("nameoid","nameoid");
put("btmname","btname");
put("lastr","islastr");
put("firstr","isfirstr");
put("lastv","islastv");
put("firstv","isfirstv");
put("creator","creator");
put("createtime","createtime");
put("lastmodifier","modifier");
put("lastmodifytime","modifytime");
put("revisionrule","revisionrule");
put("versionrule","versionrule");
put("revisionseq","revisionseq");
put("revisionvalue","revisionvalue");
put("versionseq","versionseq");
put("versionvalue","versionvalue");
put("lctid","lctid");
put("lcstatus","lcstatus");
put("ts","ts");
put("id","id");
put("name","name");
put("description","description");
put("owner","owner");
put("copyfromversion","fromversion");
}};
/**
* 主键属性
*/
public static final String OID_FIELD = "oid";
/**
* 编号的属性
*/
public static final String ID_FIELD = "id";
/**
* 生命周期的属性
*/
public static final String LC_STATUS_FIELD = "lcstatus";
/**
* 生命周期的显示文本
*/
public static final String LC_STATUS_FIELD_TEXT = "lcStatus_text";
/**
* 生命周期管理相关的字段
*/
public static final Map LIFECYCLE_MANAGE_FIELD_MAP = new HashMap(){{
put(LC_STATUS_FIELD,"生命周期值");
}};
/**
* 密级管理相关的字段
*/
public static final Map SECRET_MANAGE_FIELD_MAP = new HashMap(){{
put("secretgrade","密级值");
}};
/**
* 链接类型的字段map
*/
public static final Map LINK_TYPE_FIELD_MAP = new HashMap(){{
put("oid","主键");
put("creator","创建人");
put("createtime","创建时间");
put("lastmodifier","最后时间人");
put("lastmodifytime","最后修改时间");
put("f_oid","from端主键");
put("f_revisionoid","from端版本主键");
put("f_nameoid","from端对象主键");
put("f_btmname","from端业务类型");
put("t_oid","to端主键");
put("t_revisionoid","to端版本主键");
put("t_nameoid","to端对象主键");
put("t_btmname","to端业务类型");
put("ts","时间戳");
}};
/**
* 获取字段的类型
*/
private Map allFieldTypeMap;
/**
* 参照的信息映射,key是DO对象中的属性名称,value是参照的对象信息
*/
private List referFieldInfoList ;
/**
* 使用参照字段的映射
*/
private Map useReferMap;
/**
* 枚举字段的映射,key是数据对象里的属性,value是枚举表达式
*/
private Map enumFieldMap;
/**
* 关联表的语句
*/
private String linkTableSql;
/**
* 查询字段语句
*/
private String selectFieldSql;
/**
* 分页时增加的前缀
*/
private String selectPrefixForPage = "";
/**
* 查询语句,包含分页和排序
*/
private String whereSql;
/**
* 排序的语句
*/
private String orderSql;
/**
* 分页时增加的后缀
*/
private String whereSubfixForPage ="";
/**
* 值的映射对象
*/
private Map valuesMap;
/**
* 表格的昵称
*/
private String tableNick;
/**
* 扩展的查询列
*/
private Map extendFieldMap = new HashMap<>();
/**
* 添加构造器的内容
* @param doClass 数据对象的类
*/
public VciQueryWrapperForDO( Class> doClass) throws VciBaseException {
this(null,doClass,new PageHelper(-1),true);
}
/**
* 添加构造器的内容
* @param conditionMap 查询条件
* @param doClass 数据对象的类
*/
public VciQueryWrapperForDO(Map conditionMap, Class> doClass) throws VciBaseException {
this(conditionMap,doClass,new PageHelper(-1),true);
}
/**
* 添加构造器的内容
* @param conditionMap 查询条件
* @param doClass 数据对象的类
* @param pageHelper 分页对象
*/
public VciQueryWrapperForDO(Map conditionMap, Class> doClass, PageHelper pageHelper) throws VciBaseException {
this(conditionMap,doClass,pageHelper,true);
}
/**
* 添加构造器的内容
* @param conditionMap 查询条件
* @param doClass 数据对象的类
* @param pageHelper 分页对象
* @param autoWrapper 是否自动封装
*/
public VciQueryWrapperForDO(Map conditionMap, Class> doClass, PageHelper pageHelper, boolean autoWrapper) throws VciBaseException {
this(conditionMap,doClass,pageHelper,autoWrapper,new VciQueryWrapperOption());
}
/**
* 添加构造器的内容
* @param conditionMap 查询条件
* @param doClass 数据对象的类
* @param pageHelper 分页对象
* @param autoWrapper 是否自动封装,即构造方法就会拼接SQL;
* @param queryWrapperOption 查询的类型
*/
public VciQueryWrapperForDO(Map conditionMap, Class> doClass, PageHelper pageHelper, boolean autoWrapper, VciQueryWrapperOption queryWrapperOption) throws VciBaseException {
this.conditionMap = conditionMap;
this.doClass = doClass;
this.pageHelper = pageHelper;
this.queryWrapperOption = queryWrapperOption;
if(autoWrapper) {
wrapperSql();
}
}
/**
* 使用查询条件
* @param obj 查询对象
*/
public void initConditionByQueryObject(Object obj){
if(this.conditionMap == null){
this.conditionMap = new HashMap<>();
}
Map queryValueObject = VciBaseUtil.objectToMapString(obj);
if(!CollectionUtils.isEmpty(queryValueObject)){
this.conditionMap.putAll(queryValueObject);
}
initWhereSql();
}
/**
* 清除分页
*/
public void clearPage(){
this.pageHelper = null;
this.selectPrefixForPage = "";
this.whereSubfixForPage = "";
}
/**
* 设置新的分页信息
* @param limit 分页
* @param page 当前第几页
*/
public void setPageLimit(int limit,int page){
if(this.pageHelper == null){
this.pageHelper = new PageHelper(limit);
this.pageHelper.setPage(page);
}else{
this.pageHelper.setLimit(limit);
this.pageHelper.setPage(page);
}
initPageSql();
}
/**
* 设置分页对象
* @param pageHelper 新的分页对象
*/
public void setPageHelper(PageHelper pageHelper){
this.pageHelper = pageHelper;
initPageSql();
}
/**
* 追加in操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO in(String key, String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.IN);
return this;
}
/**
* 追加not in操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO notIn(String key,String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.NOTIN);
return this;
}
/**
* 追加等于操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO eq(String key,String value) throws VciBaseException {
addQueryMap(key,value);
return this;
}
/**
* 追加不等于操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO neq(String key,String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.NOTEQUAL);
return this;
}
/**
* 追加小于操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO less(String key,String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.LESS);
return this;
}
/**
* 追加小于等于操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO lessThan(String key,String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.LESSTHAN);
return this;
}
/**
* 追加大于操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO more(String key,String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.MORE);
return this;
}
/**
* 追加大于等于操作
* @param key 字段
* @param value 值
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO moreThan(String key,String value) throws VciBaseException {
addQueryMap(key,value, QueryOptionConstant.MORETHAN);
return this;
}
/**
* 追加为空操作
* @param key 字段
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO isNull(String key) throws VciBaseException {
addQueryMap(key,"_n", QueryOptionConstant.ISNULL);
return this;
}
/**
* 追加不为空操作
* @param key 字段
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO isNotNull(String key) throws VciBaseException {
addQueryMap(key,"_n", QueryOptionConstant.ISNOTNULL);
return this;
}
/**
* 追加密级
* @return 当前对象
* @throws VciBaseException 添加不符合要求的时候会抛出异常
*/
public VciQueryWrapperForDO secret() throws VciBaseException{
String secretSql = getLessThanUserSecretSql();
addQueryMap("secretGrade",secretSql,QueryOptionConstant.LESSTHAN );
return this;
}
/**
* 添加查询条件
* @param key 字段
* @param value 值
*/
public void addQueryMap(String key, String value) {
addQueryMap(key,value,null);
}
/**
* 添加查询条件
* @param key 字段
* @param value 值
* @param operation 操作类型
*/
public void addQueryMap(String key, String value, String operation) {
VciBaseUtil.alertNotNull(key,"查询条件的名称");
if(StringUtils.isNotBlank(value)) {
if (this.conditionMap == null) {
this.conditionMap = new HashMap<>();
}
if (operation == null) {
operation = "";
}
this.conditionMap.put(key, operation + value);
}
}
/**
* 加入自定义的sql
* @param key key
* @param sql sql的信息
*/
public void addCustomSql(String key,String sql){
VciBaseUtil.alertNotNull(key,"自定义SQL的KEY",sql,"自定义的SQL语句");
if(StringUtils.isNotBlank(sql)){
if (this.customerSqlMap == null) {
this.customerSqlMap = new HashMap<>();
}
this.customerSqlMap.put(key,sql);
}
}
/**
* 添加扩展的查询字段
* @param fieldName 字段的名称
*/
public void addExtendField(String fieldName){
addExtendField(fieldName,fieldName);
}
/**
* 添加扩展的查询字段
* @param fieldName 字段名称
* @param nickName 昵称
*/
public void addExtendField(String fieldName,String nickName){
extendFieldMap.put(fieldName,nickName);
}
public Map getConditionMap() {
return conditionMap;
}
public void setConditionMap(Map conditionMap) {
this.conditionMap = conditionMap;
}
/**
* 移除查询条件,包括自定义的SQL
* @param key 查询条件
*/
public void removeQueryMap(String key){
VciBaseUtil.alertNotNull(key,"查询条件的名称");
if (this.conditionMap == null) {
this.conditionMap = new HashMap<>();
}
if(this.conditionMap.containsKey(key)){
this.conditionMap.remove(key);
}
if(this.customerSqlMap == null){
this.customerSqlMap = new HashMap<>();
}
if(this.customerSqlMap.containsKey(key)){
this.customerSqlMap.remove(key);
}
initWhereSql();
}
/**
* 封装SQL语句
*/
public void wrapperSql() throws VciBaseException {
VciBaseUtil.alertNotNull(this.doClass,"数据对象类");
//首先是要先找属性字段
initFieldNameMap();
//组建查询字段
initSelectSql();
//组建条件语句
initWhereSql();
//组建和排序的SQL
initPageSql();
}
/**
* 初始化排序的SQL
*/
private void initPageSql() {
if(this.pageHelper != null) {
this.pageHelper.setNick(this.getTableNick());
//因为参照关联的时候,是把字段最小化当成表格的昵称的,所以直接判断即可
if (StringUtils.isNotBlank(this.pageHelper.getSort())) {
//排序这个都有没有分页都没关系
this.pageHelper.getUnNickField().addAll(this.extendFieldMap.values().stream().map(s->s.toLowerCase(Locale.ROOT)).collect(Collectors.toList()));
this.orderSql = this.pageHelper.getOrdersql();
}
if (this.pageHelper.getLimit() > 0) {
DataBaseEnum db = DataBaseEnum.forValue(DATABASE_PLATFORM);
switch (db){
case SQLITE:
this.whereSubfixForPage = " limit " + this.pageHelper.getLimit() + " offset " + this.pageHelper.getLimit()*(this.pageHelper.getPage()-1);
break;
case MYSQL:
//没有用分页插件,项目的数量不会太多,所以直接sql里组装
this.whereSubfixForPage = " limit " + this.pageHelper.getLimit()*(this.pageHelper.getPage()-1) + "," + this.pageHelper.getLimit() ;
break;
case SQL_SERVER:
this.selectPrefixForPage = "select top (" + this.pageHelper.getLimit() + ") * from (select A.*,ROW_NUMBER() OVER(" + (StringUtils.isNotBlank(this.orderSql)?this.orderSql:" order by oid") + " AS RowId from (";
this.whereSubfixForPage = " ) as A ) as B where B.RowId > "
+ (this.pageHelper.getLimit()*(this.pageHelper.getPage()-1) + 1);
break;
default:
List compatibilityPageSqlList = new ArrayList<>();
String[] temp = this.selectFieldSql.split(",");
if(temp!=null && temp.length>0){
for (int i = 0; i < temp.length; i++) {
String record = temp[i];
if(record.contains(" as ")){
compatibilityPageSqlList.add(record.split(" as ")[1]);
}
}
}
this.selectPrefixForPage = (USER_TABLE_COMPATIBILITY?("select " + compatibilityPageSqlList.stream().collect(Collectors.joining(","))):" select *") +" from (select A.*,rownum RN from (";
//page = 2, limit = 25, 所以是大于等于(2-1)*25 + 1 == 26.,小于 2*25+1 ==51,就是1,到25 ;26到50,
this.whereSubfixForPage = " ) A where rownum < " + (this.pageHelper.getLimit()*this.pageHelper.getPage() + 1) + ") where RN >= "
+ (this.pageHelper.getLimit()*(this.pageHelper.getPage()-1) + 1);
break;
}
}
}
}
/**
* 初始化条件语句
*/
public void initWhereSql() {
List andSql = new ArrayList<>();
List orSql = new ArrayList<>();
if(!CollectionUtils.isEmpty(this.conditionMap)){
Map orConditionMap = new HashMap<>();
Map andCondtionMap = new HashMap<>();
//先分离or的查询条件,另外当查询条件是空的时候也不查询
this.conditionMap.forEach((k,v) -> {
if(QUERY_FIELD_SECRET.equalsIgnoreCase(k)){
if(!Boolean.valueOf(v)){
this.queryWrapperOption.setThisObjectQuerySecret(false);
}
}else if(QUERY_FIELD_DATARIGHT.equalsIgnoreCase(k)){
//
}else {
if (StringUtils.isNotBlank(v) && (k.contains(".") || k.endsWith("_begin") || k.endsWith("_end") || this.allFieldNameMap.containsKey(k.toLowerCase().trim()))) {
if (v.startsWith(QueryOptionConstant.OR)) {
orConditionMap.put(k, v);
} else {
andCondtionMap.put(k, v);
}
}
}
} );
andCondtionMap.forEach((k,v) -> {
andSql.add(getConditionSql(k.toLowerCase(),v));
});
orConditionMap.forEach((k,v) -> {
orSql.add(getConditionSql(k.toLowerCase(),v.substring(QueryOptionConstant.OR.length())));
});
}
List appendWhereSqlList = new ArrayList<>();
if(!CollectionUtils.isEmpty(customerSqlMap)){
//说明有自定义的SQL,这种直接添加即可
customerSqlMap.forEach((k,v)->{
if(v.startsWith(QueryOptionConstant.OR)){
orSql.add(v.substring(QueryOptionConstant.OR.length()));
}else if(v.startsWith(QueryOptionConstant.NO_OR_AND)){
appendWhereSqlList.add(v.substring(QueryOptionConstant.NO_OR_AND.length()));
}else{
andSql.add(v);
}
});
}
//组合起来
StringBuilder andSb = new StringBuilder();
andSql.stream().forEach( s -> {
andSb.append(s).append(SPACE).append(QueryOptionConstant.AND).append(SPACE);
});
String andString = andSb.toString().trim();
String endWithSql = QueryOptionConstant.AND;
if(andString.endsWith(endWithSql) ){
andString = andString.substring(0,andString.length() - endWithSql.length());
}
String orString = orSql.stream().collect(Collectors.joining(" or "));
if(StringUtils.isNotBlank(orString)){
this.whereSql = SPACE + (StringUtils.isBlank(andString)?(orString):("(" + SPACE + andString + SPACE + ") and (" + SPACE + orString + SPACE + ")")) + SPACE;
}else{
this.whereSql = andString + SPACE;
}
if(this.queryWrapperOption.getThisObjectQuerySecret()){
//说明要添加密级
this.whereSql += " and ( " + this.getTableNick() + ".secretGrade <= " + VciBaseUtil.getCurrentUserSecret() + ") ";
}
if(this.queryWrapperOption.getThisObjectQueryRevision() && this.queryWrapperOption.getThisObjectQueryLastRevision()){
//说明查询最后的版本
if(USER_TABLE_COMPATIBILITY){
this.whereSql += " and ( " + this.getTableNick() + "." + BASE_MODEL_COMPATIBILITY_MAP.getOrDefault("lastr","lastr") + " = '1' and " + this.getTableNick() + "." + BASE_MODEL_COMPATIBILITY_MAP.getOrDefault("lastv","lastv") + "= '1' ) ";
}else {
this.whereSql += " and ( " + this.getTableNick() + ".LastR = '1' and " + this.getTableNick() + ".LastV = '1' ) ";
}
}
if(this.queryWrapperOption.getThisObjectQueryRevision() && this.queryWrapperOption.getThisObjectQueryRelease()){
//说明查询查询最后的版本
this.whereSql += " and releaseobj.oid is not null ";
}
if(!CollectionUtils.isEmpty(appendWhereSqlList)){
if(StringUtils.isBlank(this.whereSql)){
this.whereSql = " 1 = 1 ";
}
appendWhereSqlList.stream().forEach(sql->{
this.whereSql += (sql + SPACE);
});
}
}
/**
* 获取查询部分的sql,
* @param key 查询条件
* @param value 查询的值
* @return 不包含and或者or
*/
private String getConditionSql(String key,String value){
boolean isReferField = false;
//因为数据库的字段和属性的字段不相同
boolean hasNick = false;
if(StringUtils.isNotBlank(getTableNick()) && key.startsWith(getTableNick() + ".")){
hasNick = true;
}else{
if(key.contains(".")){
isReferField = true;
}
}
String selectKey = key;
if(hasNick){
//直接使用传入进来的
}else if(isReferField){
//参照的时候,传递的xxxx.yy的形式,其中xxx是当前对象里的属性,而yy是参照的业务类型中的数据库属性
String[] referKeyInfos = key.split("\\.");
String referKeyLower = referKeyInfos[0].toLowerCase().trim();
if(this.allFieldNameMap.containsKey(referKeyLower)){
String thisObjectKey = this.allFieldNameMap.get(referKeyLower);
selectKey = thisObjectKey.toLowerCase() + "." + referKeyInfos[1];
}else{
//增加自定义的条件
selectKey = key;
}
}else if(selectKey.endsWith("_begin") && this.allFieldNameMap.containsKey(selectKey.substring(0,selectKey.length()-6).toLowerCase().trim())){
String field = (selectKey.substring(0,selectKey.length()-6).toLowerCase().trim());
return getTableNick()+"." + field + SPACE + ">=" + SPACE + getStringValueInWhere(value,field) + SPACE;
}else if(selectKey.endsWith("_end") && this.allFieldNameMap.containsKey(selectKey.substring(0,selectKey.length()-4).toLowerCase().trim())){
String field = (selectKey.substring(0,selectKey.length()-4).toLowerCase().trim());
return getTableNick()+"." + field + SPACE + "<=" + SPACE + getStringValueInWhere(value,field) + SPACE;
}else{
if(!this.allFieldNameMap.containsKey(key.toLowerCase().trim())){
if(this.allFieldNameMap.containsValue(key.toLowerCase().trim())){
//传递的属性上的内容
selectKey = this.allFieldNameMap.entrySet()
.stream()
.filter(entry -> key.equalsIgnoreCase(entry.getValue()))
.map(Map.Entry::getKey).collect(Collectors.joining());
}
}
if(StringUtils.isNotBlank(getTableNick())){
selectKey = getTableNick()+"." + selectKey;
}
}
StringBuilder sql = new StringBuilder();
if (value.startsWith(QueryOptionConstant.IN)) {
sql.append(selectKey)
.append(SPACE)
.append("in")
.append(SPACE)
.append("(")
.append(value.replace(QueryOptionConstant.IN, ""))
.append(")");
} else if (value.startsWith(QueryOptionConstant.NOTIN)) {
sql.append(selectKey)
.append(SPACE)
.append("not in")
.append(SPACE)
.append("(")
.append(value.replace(QueryOptionConstant.NOTIN, ""))
.append(")");
} else if (value.startsWith(QueryOptionConstant.ISNOTNULL)) {
sql.append(selectKey)
.append(SPACE)
.append(" is not null");
} else if (value.startsWith(QueryOptionConstant.NOTEQUAL)) {
value = value.replace(QueryOptionConstant.NOTEQUAL, "");
if(isReferField){
value = "'" + value + "'";
}else{
value = getStringValueInWhere(value,key);
}
sql.append(selectKey)
.append(SPACE)
.append(QueryOptionConstant.NOTEQUAL)
.append(SPACE)
.append(value);
}else if (value.startsWith(QueryOptionConstant.MORETHAN)) {
value = value.replace(QueryOptionConstant.MORETHAN, "");
if(isReferField){
value = "'" + value + "'";
}else{
value = getStringValueInWhere(value,key);
}
sql.append(selectKey)
.append(SPACE)
.append(QueryOptionConstant.MORETHAN)
.append(SPACE)
.append(value);
} else if (value.startsWith(QueryOptionConstant.MORE)) {
value = value.replace(QueryOptionConstant.MORE, "");
if(isReferField){
value = "'" + value + "'";
}else{
value = getStringValueInWhere(value,key);
}
sql.append(selectKey)
.append(SPACE)
.append(QueryOptionConstant.MORE)
.append(SPACE)
.append(value);
} else if (value.startsWith(QueryOptionConstant.LESSTHAN)) {
value = value.replace(QueryOptionConstant.LESSTHAN, "");
if(isReferField){
value = "'" + value + "'";
}else{
value = getStringValueInWhere(value,key);
}
sql.append(selectKey)
.append(SPACE)
.append(QueryOptionConstant.LESSTHAN)
.append(SPACE)
.append(value);
}else if (value.startsWith(QueryOptionConstant.LESS)) {
value = value.replace(QueryOptionConstant.LESS, "");
if(isReferField){
value = "'" + value + "'";
}else{
value = getStringValueInWhere(value,key);
}
sql.append(selectKey)
.append(SPACE)
.append(QueryOptionConstant.LESS)
.append(SPACE)
.append(value);
} else if (value.startsWith(QueryOptionConstant.ISNULL)) {
sql.append(selectKey)
.append(SPACE)
.append(" is null");
} else if(value.contains("*")){
//说明是like,或者lefe like ,right like
sql.append(selectKey)
.append(SPACE)
.append("like")
.append(SPACE)
.append("'")
.append(value.replace("*","%"))
.append("'")
.append(SPACE);
} else {
if(isReferField){
value = "'" + value + "'";
}else{
value = getStringValueInWhere(value,key);
}
sql.append(selectKey)
.append(SPACE)
.append(QueryOptionConstant.EQUAL)
.append(SPACE)
.append(value);
}
sql.append(SPACE);
return sql.toString();
}
/**
* 获取查询条件中的值的,处理不同的类型
* @param value 值
* @param field 字段名称
* @return 日期或者时间格式会包括to_date,字符串会加'
*/
private String getStringValueInWhere(String value,String field){
VciFieldTypeEnum fieldTypeEnum = this.allFieldTypeMap.get(field.toLowerCase());
if("ts".equals(field.toLowerCase())){
return "to_timestamp('" + value +"', '" + DATETIME_FORMAT + ".ff')";
}
DateConverter dateConverter = new DateConverter();
if(VciFieldTypeEnum.VTDateTime.equals(fieldTypeEnum)){
//实际上,数据库都是timestamp的类型.
dateConverter.setAsText(value);
return "to_date('" + dateConverter.getAsText(VciDateUtil.DateTimeFormat) + "','"+ DATETIME_FORMAT +"')";
}else if(VciFieldTypeEnum.VTDate.equals(fieldTypeEnum)){
dateConverter.setAsText(value);
return "to_date('" + dateConverter.getAsText(VciDateUtil.DateFormat) + "','"+ DATE_FORMAT +"')";
}else if(VciFieldTypeEnum.VTDouble.equals(fieldTypeEnum)
|| VciFieldTypeEnum.VTLong.equals(fieldTypeEnum)
|| VciFieldTypeEnum.VTInteger.equals(fieldTypeEnum)){
return value;
}else{
return "'" + value + "'";
}
}
/**
* 默认的时间格式
*/
private static final String DATETIME_FORMAT = "yyyy-mm-dd hh24:mi:ss";
/**
* 日期格式
*/
private static final String DATE_FORMAT = "yyyy-mm-dd";
/**
* 初始化查询字段的语句,这里不处理分页的内容
*/
private void initSelectSql() throws VciBaseException {
if(!CollectionUtils.isEmpty(this.allFieldNameMap)){
String tableName = getTableName();
if(StringUtils.isBlank(this.getTableNick())){
if(tableName.contains("_")){
this.setTableNick(tableName.substring(tableName.indexOf("_")+1));
}else {
this.setTableNick(tableName);
}
this.setTableNick(this.getTableNick() + "0");
}
StringBuilder sb = new StringBuilder();
sb.append("select").append(SPACE);
if(isDistinct()){
sb.append("DISTINCT").append(SPACE);
}
this.allFieldNameMap.forEach((k,v) -> {
sb.append(this.getTableNick()).append(".").append(k.toUpperCase()).append(xmlTypeFieldList.contains(k.toLowerCase(Locale.ROOT))?".getclobval()":"").append(USER_TABLE_COMPATIBILITY?(" as " + k):" ").append(",").append(SPACE);
});
if(!CollectionUtils.isEmpty(extendFieldMap)){
extendFieldMap.forEach((k,v)->{
sb.append(SPACE).append(k).append(SPACE).append("as").append(SPACE).append(v).append(SPACE).append(",").append(SPACE);
});
}
StringBuilder joinSqlSb = new StringBuilder();
Set joinedFieldSet = new HashSet<>();
if(!CollectionUtils.isEmpty(this.referFieldInfoList)){
//说明有参照,key
this.referFieldInfoList.stream().forEach(s ->{
//第一次的时候,referBtmType还是表达式
String exp = s.getReferBtmTypeExp();
if(StringUtils.isBlank(exp)){
throw new VciBaseException("{0}中属性{1}的注解中referColumn为空",new Object[]{this.doClass.getName() , s.getShowReferFieldName()});
}
if(!exp.contains(".")){
throw new VciBaseException("{0}中属性{1}的注解中referColumn的格式不正确,必须为xxx.yy方式,xxx是当前对象中使用参照的属性名称,yy是参照的业务类型中的字段名称",new Object[]{this.doClass.getName() , s.getShowReferFieldName()});
}
//比如 pkPerson和pkPersonName. 参照person这个业务类型的name属性,pkPerson对应的数据库字段为personoid
//当前数据对象的属性字段,就等于pkPerson
String thisFieldName = exp.substring(0,exp.indexOf("."));
//当前数据对象的属性字段小写 pkperson
String thisFieldNameLow = thisFieldName.toLowerCase().trim();
//引用的业务类型中的属性字段,name
String referBtmTypeFieldName = exp.substring(exp.indexOf(".") + 1);
if(this.useReferMap.containsKey(thisFieldNameLow)){
s.setReferBtmType(this.useReferMap.get(thisFieldNameLow));
String primaryKey = OID_FIELD;
if(USER_TABLE_COMPATIBILITY){
//说明需要兼容老的平台
//比如 pkuser.name as pkUser.name 对应老平台的就是pkuser.plname as pkUser.name
//left join vcibt_user pkuser on xxx.pkuser = pkuser.oid 对应老平台是 left join pluser pkuser on xxx.pkuser = pkuser.pluid
String referBtmTypeLower = s.getReferBtmType().toLowerCase().trim();
if(USER_TABLE_COMPATIBILITY_BTM_MAP.containsKey(referBtmTypeLower)){
s.setReferTableName(USER_TABLE_COMPATIBILITY_BTM_MAP.get(referBtmTypeLower));
String fieldKey = referBtmTypeLower + USER_TABLE_COMPATIBILITY_FIELD_SEP + referBtmTypeFieldName.trim().toLowerCase();
if(USER_TABLE_COMPATIBILITY_FIELD_MAP.containsKey(fieldKey)){
referBtmTypeFieldName = USER_TABLE_COMPATIBILITY_FIELD_MAP.get(fieldKey);
}
String primaryKeyCompa = referBtmTypeLower + USER_TABLE_COMPATIBILITY_FIELD_SEP + primaryKey;
if(USER_TABLE_COMPATIBILITY_FIELD_MAP.containsKey(primaryKeyCompa)){
primaryKey = USER_TABLE_COMPATIBILITY_FIELD_MAP.get(primaryKeyCompa);
}
if(OID_FIELD.equalsIgnoreCase(s.getReferBtmTypeField())){
s.setReferBtmTypeField(primaryKey);
}
}else{
s.setReferTableName(VciBaseUtil.getTableName(s.getReferBtmType()));
}
}else {
s.setReferTableName(VciBaseUtil.getTableName( s.getReferBtmType()));
}
s.setUseReferFieldName(thisFieldName);
s.setUseReferDbFieldName(this.allFieldNameMap.get(thisFieldNameLow));
// pkperson.name as pkPersonName
sb.append(thisFieldNameLow)
.append(".")
.append(referBtmTypeFieldName)
.append(SPACE)
.append("as")
.append(SPACE)
.append(s.getShowReferFieldName())
.append(",")
.append(SPACE);
if(!joinedFieldSet.contains(thisFieldNameLow)) {
//left join vcibt_person pkperson on xxx.personoid = pkperson.oid
joinSqlSb.append(" left join ")
.append(s.getReferTableName())
.append(SPACE)
.append(thisFieldNameLow)
.append(SPACE)
.append("on")
.append(SPACE)
.append(this.getTableNick())
.append(".")
.append(s.getUseReferDbFieldName())
.append(SPACE)
.append("=")
.append(SPACE)
.append(thisFieldNameLow)
.append(".")
.append(StringUtils.isBlank(s.getReferBtmTypeField())?primaryKey:s.getReferBtmTypeField())
.append(SPACE);
joinedFieldSet.add(thisFieldNameLow);
}
}else{
if(USER_TABLE_COMPATIBILITY){
//如果是兼容模式的话,可以直接查询
sb.append(thisFieldNameLow)
.append(".")
.append(referBtmTypeFieldName)
.append(SPACE)
.append("as")
.append(SPACE)
.append(s.getShowReferFieldName())
.append(",")
.append(SPACE);
}else {
throw new VciBaseException("{0}中属性{1}的注解中referColumn的内容不正确,使用参照的属性{2}不存在", new Object[]{this.doClass.getName(), s.getShowReferFieldName(), thisFieldName});
}
}
});
}
if(this.queryWrapperOption.getThisObjectQueryRevision() && this.queryWrapperOption.getThisObjectQueryRelease()){
joinSqlSb.append( " left join ")
.append("vcibt_releasedobj")
.append(SPACE)
.append("releaseobj")
.append(SPACE)
.append("on")
.append(SPACE)
.append(this.getTableNick())
.append(".")
.append("nameoid")
.append(SPACE)
.append("=")
.append(SPACE)
.append("releaseobj")
.append(".")
.append("nameoid")
.append(SPACE);
}
this.selectFieldSql = sb.toString().trim();
if(this.selectFieldSql.endsWith(",")){
this.selectFieldSql = this.selectFieldSql.substring(0,this.selectFieldSql.length() -1) + SPACE;
}
this.linkTableSql = joinSqlSb.toString();
}
}
/**
* 获取数据库表的名称
* @return 数据库表的名称,如果是视图的话,请不要使用这个类来查询
*/
public String getTableName(){
if(this.doClass.isAnnotationPresent(VciLinkType.class)){
VciLinkType linkType = this.doClass.getDeclaredAnnotation(VciLinkType.class);
String tableName = linkType.tableName();
if(StringUtils.isBlank(tableName)){
return VciBaseUtil.getLinkTableName(linkType.name());
}else{
return tableName;
}
}else if(this.doClass.isAnnotationPresent(VciBtmType.class)){
VciBtmType btmType = this.doClass.getDeclaredAnnotation(VciBtmType.class);
String tableName = btmType.tableName();
if(StringUtils.isBlank(tableName)){
return VciBaseUtil.getTableName(btmType.name());
}else{
return tableName;
}
}else{
String name = this.doClass.getSimpleName();
if(name.endsWith("DO")){
name = name.substring(0,name.length()-2);
}
return VciBaseUtil.getTableName(name);
}
}
/**
* 初始化变量
*/
private void initMap(){
if(this.allFieldNameMap == null){
this.allFieldNameMap = new HashMap<>();
}else{
this.allFieldNameMap.clear();
}
if(this.allFieldTypeMap == null){
this.allFieldTypeMap = new HashMap<>();
}else{
this.allFieldTypeMap.clear();;
}
if(this.referFieldInfoList == null){
this.referFieldInfoList = new ArrayList<>();
}else{
this.referFieldInfoList.clear();
}
if(this.useReferMap == null){
this.useReferMap = new HashMap<>();
}else{
this.useReferMap.clear();
}
if(this.enumFieldMap == null){
this.enumFieldMap = new HashMap<>();
}else{
this.enumFieldMap.clear();
}
}
/**
* 获取类中的字段映射
*/
public void initFieldNameMap(){
initMap();
List allField = VciBaseUtil.getAllFieldForObj(this.doClass);
//是否有版本管理
boolean hasRevisionManage = getRevisionManage();
if(hasRevisionManage){
this.queryWrapperOption.setThisObjectQueryRevision(true);
}
//是否有生命周期管理
boolean hasLifeCycleManage = getLifeCycleManage();
if(hasLifeCycleManage){
this.queryWrapperOption.setThisObjectQueryLifeCycle(true);
}
//是否有密级管理
boolean hasSecretManage = getSecretManage();
if(!hasSecretManage){
this.queryWrapperOption.setThisObjectQuerySecret(false);
}else{
//有密级,还得看是否开启密级
if(this.queryWrapperOption.getThisObjectQuerySecret() == null){
this.queryWrapperOption.setThisObjectQuerySecret(DEFAULT_QUERY_SECRET);
}
}
//数据权限怎么弄
//TODO 数据权限需要处理 weidy
if(allField!=null&&allField.size()>0){
for(Field field : allField){
field.setAccessible(true);
if(field.isAnnotationPresent(Id.class)){
this.oidFieldName = field.getName();
}
if(!field.getName().equals("serialVersionUID") ){
Class fieldTypeClass = field.getType();
if(VciBaseUtil.isBasicType(fieldTypeClass)){
String fieldName = field.getName();
if(!hasRevisionManage && REVISION_MANAGE_FIELD_MAP.containsKey(fieldName.toLowerCase()) && !USER_TABLE_COMPATIBILITY){
//不管理版本
}else if(!hasLifeCycleManage && LIFECYCLE_MANAGE_FIELD_MAP.containsKey(fieldName.toLowerCase()) && !USER_TABLE_COMPATIBILITY){
//不管理生命周期
}else if(!hasSecretManage && SECRET_MANAGE_FIELD_MAP.containsKey(fieldName.toLowerCase())){
//不管理密级
}else {
String clientBoAttrName = VciBaseUtil.getCboAttrNameFromField(field, this.doClass);
if(USER_TABLE_COMPATIBILITY){
clientBoAttrName = BASE_MODEL_COMPATIBILITY_MAP.getOrDefault(clientBoAttrName,clientBoAttrName);
}
if (field.isAnnotationPresent(Transient.class)) {
//说明这个不是持久化的
Transient trans = field.getAnnotation(Transient.class);
if (StringUtils.isNotBlank(trans.referColumn()) && trans.referColumn().contains(".")) {
//说明是参照的字段.获取参照的内容
VciReferFieldInfo vciReferFieldInfo = new VciReferFieldInfo();
vciReferFieldInfo.setShowReferFieldName(fieldName);
vciReferFieldInfo.setShowReferDbFieldName(clientBoAttrName);
vciReferFieldInfo.setReferBtmTypeExp(trans.referColumn());
vciReferFieldInfo.setReferBtmTypeField(trans.valueField());
this.referFieldInfoList.add(vciReferFieldInfo);
}
if(USER_TABLE_COMPATIBILITY && "lctid".equalsIgnoreCase(fieldName)){
this.allFieldTypeMap.put("lctid", VciFieldTypeEnum.VTString);
}
} else {
allFieldNameMap.put(clientBoAttrName.toLowerCase().trim(), field.getName());
if(field.isAnnotationPresent(XmlType.class)){
xmlTypeFieldList.add(clientBoAttrName.toLowerCase(Locale.ROOT).trim());
}
VciFieldTypeEnum fieldTypeEnum = null;
if (field.isAnnotationPresent(VciFieldType.class)) {
VciFieldType vciFieldType = field.getAnnotation(VciFieldType.class);
fieldTypeEnum = VciFieldTypeEnum.forValue(vciFieldType.value().name());
} else {
//根据数据的类型判断
if (VciBaseUtil.inArray(new Object[]{Double.class, double.class}, fieldTypeClass)) {
fieldTypeEnum = VciFieldTypeEnum.VTDouble;
} else if (VciBaseUtil.inArray(new Object[]{Integer.class, int.class}, fieldTypeClass)) {
fieldTypeEnum = VciFieldTypeEnum.VTInteger;
} else if (VciBaseUtil.inArray(new Object[]{Long.class, long.class}, fieldTypeClass)) {
fieldTypeEnum = VciFieldTypeEnum.VTLong;
} else if (Date.class.equals(fieldTypeClass)) {
fieldTypeEnum = VciFieldTypeEnum.VTDateTime;
} else {
fieldTypeEnum = VciFieldTypeEnum.VTString;
}
}
this.allFieldTypeMap.put(clientBoAttrName.toLowerCase().trim(), fieldTypeEnum);
if (field.isAnnotationPresent(VciUseEnum.class)) {
//说明是枚举值的字段
VciUseEnum useEnum = field.getAnnotation(VciUseEnum.class);
this.enumFieldMap.put(useEnum.showTextField(), useEnum.value());
}
if (field.isAnnotationPresent(VciUseRefer.class)) {
VciUseRefer useRefer = field.getAnnotation(VciUseRefer.class);
this.useReferMap.put(clientBoAttrName.toLowerCase().trim(), useRefer.value());
}
}
}
}else{
//不是基本类型的,那一定不是要的属性
}
}
}
}
}
/**
* 根据父查询子节点
* @param treeQueryObject 树形查询条件和配置
* @param parentQueryOption 父查询配置,是自身属性,还是链接类型
*/
public void parentQueryChild(TreeQueryObject treeQueryObject,VciParentQueryOption parentQueryOption) {
if (treeQueryObject == null){
treeQueryObject = new TreeQueryObject();
}
VciQueryWrapperOption queryWrapperOption = new VciQueryWrapperOption();
if(treeQueryObject.isQueryAllRev()){
queryWrapperOption.setThisObjectQueryLastRevision(false);
queryWrapperOption.setThisObjectQueryRelease(false);
}
this.conditionMap = treeQueryObject.getConditionMap();
this.pageHelper = new PageHelper(-1);
this.queryWrapperOption = queryWrapperOption;
if(parentQueryOption!=null&& !parentQueryOption.isLinkTypeFlag() &&
StringUtils.isNotBlank(parentQueryOption.getParentFieldName())){
//说明是根据上级的字段来查询
if(StringUtils.isNotBlank(treeQueryObject.getParentOid()) ){
//说明传递了上级的
if(treeQueryObject.isQueryAllLevel()){
this.addCustomSql("startwithparent" + parentQueryOption.getParentFieldName() ,
QueryOptionConstant.NO_OR_AND + " start with " + this.getTableNick() + "." + parentQueryOption.getParentFieldName() + " = '" + treeQueryObject.getParentOid().trim()
+ "' connect by prior " + this.getTableNick() + "." + this.getOidFieldName() + " = " + this.getTableNick() + "." + parentQueryOption.getParentFieldName());
}else {
//根据上级查询直属下级
this.eq(parentQueryOption.getParentFieldName(), treeQueryObject.getParentOid());
}
}else{
if(treeQueryObject.isQueryAllLevel()){
//全部的层级都要查询,我们使用start with先查询出结果后,再匹配查询条件
this.addCustomSql("startwithparent" + parentQueryOption.getParentFieldName() , QueryOptionConstant.NO_OR_AND + "start with " + this.getTableNick() + "." + parentQueryOption.getParentFieldName()
+ " is null connect by prior " + this.getTableNick() + "." + this.getOidFieldName() + " = " + this.getTableNick() + "." + parentQueryOption.getParentFieldName() );
}else{
this.isNull(parentQueryOption.getParentFieldName());
}
}
}else if(parentQueryOption!=null&& parentQueryOption.isLinkTypeFlag() && StringUtils.isNotBlank(parentQueryOption.getLinkTypeName())){
if(treeQueryObject.isQueryAllLevel()){
this.in(this.getOidFieldName(),
" select " + (parentQueryOption.isQueryFromToFlag()?" f_oid ":" t_oid ") +
" from " + VciBaseUtil.getLinkTableName(parentQueryOption.getLinkTypeName()) + " start with " +
(parentQueryOption.isQueryFromToFlag()?" t_oid ":" f_oid ") +
(StringUtils.isNotBlank(treeQueryObject.getParentOid())?(" = '" + treeQueryObject.getParentOid().trim() + "'"):" is null ") + " connect by prior " +
(parentQueryOption.isQueryFromToFlag()?" t_oid = f_oid ":"f_oid = t_oid "));
}else{
//查询直属下级
this.in(this.getOidFieldName()," select " + (parentQueryOption.isQueryFromToFlag()?" f_oid ":" t_oid ") +
" from " + VciBaseUtil.getLinkTableName(parentQueryOption.getLinkTypeName()) + " where " +
(parentQueryOption.isQueryFromToFlag()?" t_oid ":" f_oid ") +
(StringUtils.isNotBlank(treeQueryObject.getParentOid())?(" = '" + treeQueryObject.getParentOid().trim() + "'"):" is null "));
}
}else{
//throw new VciBaseException("parentQueryOption参数错误,要么是指定上级的属性,要么是链接类型的方式");
}
wrapperSql();
}
/**
* 子查询父
* @param parentQueryOption 上级的配置,是自身属性,还是链接类型
*/
public void childQueryParent(VciParentQueryOption parentQueryOption){
VciBaseUtil.alertNotNull(parentQueryOption,"上级查询配置");
String valueSql = (StringUtils.isNotBlank(parentQueryOption.getfOid()))?(" = '" + parentQueryOption.getfOid() + "'"):(" is null");
if(!parentQueryOption.isLinkTypeFlag() &&
StringUtils.isNotBlank(parentQueryOption.getParentFieldName())){
//说明是自身有上级的属性
this.addCustomSql("startwithchild" +parentQueryOption.getParentFieldName(),
QueryOptionConstant.NO_OR_AND + "start with " + this.getTableNick() + "." +
(parentQueryOption.isHasSelf()?("oid" + valueSql):("oid = (select " + parentQueryOption.getParentFieldName() + " from " + this.getTableName() + " where oid " + valueSql + ") ")) +
" connect by prior " + this.getTableNick() + "."+ parentQueryOption.getParentFieldName() + " = " + this.getTableNick() + ".oid ");
}else if(parentQueryOption.isLinkTypeFlag()){
this.in(this.getOidFieldName()," select " + (parentQueryOption.isQueryFromToFlag()?"t_oid ":"f_oid") +
" from " + VciBaseUtil.getLinkTableName(parentQueryOption.getLinkTypeName()) + " start with " +
(parentQueryOption.isQueryFromToFlag()?" f_oid ":" t_oid" ) + valueSql +
" connect by prior " +
(parentQueryOption.isQueryFromToFlag()?" f_oid = t_oid ":"t_oid = f_oid "));
}else{
throw new VciBaseException("parentQueryOption参数错误,要么是指定上级的属性,要么是链接类型的方式");
}
}
/**
* 获取是否管理密级
* @return true表示管理
*/
private boolean getSecretManage() {
if(this.doClass.isAnnotationPresent(VciBtmType.class)){
VciBtmType vciBtmType = this.doClass.getDeclaredAnnotation(VciBtmType.class);
return vciBtmType.secretAble();
}
return false;
}
/**
* 获取是否管理生命周期
* @return true表示管理
*/
private boolean getLifeCycleManage() {
if(this.doClass.isAnnotationPresent(VciBtmType.class)){
VciBtmType vciBtmType = this.doClass.getDeclaredAnnotation(VciBtmType.class);
if(StringUtils.isNotBlank(vciBtmType.lifeCycle()) && !FrameWorkLcStatusConstant.EMTYPE_LIFE_CYCLE.equalsIgnoreCase(vciBtmType.lifeCycle()) ){
return true;
}
}
return false;
}
/**
* 是否包含版本管理
* @return true表示管理版本
*/
private boolean getRevisionManage() {
if(this.doClass.isAnnotationPresent(VciBtmType.class)){
VciBtmType vciBtmType = this.doClass.getDeclaredAnnotation(VciBtmType.class);
if(StringUtils.isNotBlank(vciBtmType.revisionRule()) || vciBtmType.revisionRuleInput()){
return true;
}
}
return false;
}
/**
* 转换为db的字段
* @return 字段和查询的值
*/
public Map switchConditionMap(){
Map queryMap = new HashMap<>();
if(!CollectionUtils.isEmpty(this.conditionMap)){
//TODO: 转换前的字段和转换后的字段不应该同时存在,应该都统一使用转换后的字段做查询条件
/*this.conditionMap.forEach((key,value)->{
queryMap.put(key,value);
});*/
//我们转换一下,直接set,如果还有重复的就只能自行解决
this.allFieldNameMap.forEach((dbField,field)->{
if(conditionMap.containsKey(field)){
queryMap.put(dbField,this.conditionMap.get(field));
}
});
}
return queryMap;
}
/**
* 获取关联表格的内容
* @return 关联表格的sql
*/
public String getLinkTableSql() {
return linkTableSql;
}
public void setLinkTableSql(String linkTableSql) {
this.linkTableSql = linkTableSql;
}
/**
* 追加连接的表
* @param linkTableSql 连接表的sql
*/
public void addLinkTableSql(String linkTableSql){
this.linkTableSql += (SPACE + linkTableSql + SPACE);
}
public String getSelectFieldSql() {
initWhereSql();
if(this.pageHelper!=null&& this.pageHelper.getLimit()>0){
return this.selectPrefixForPage + this.selectFieldSql;
}
return selectFieldSql;
}
public void setSelectFieldSql(String selectFieldSql) {
this.selectFieldSql = selectFieldSql;
}
/**
* 添加自定义的查询字段
* @param sql 添加的Sql
*/
public void appendSelectField(String sql){
this.selectFieldSql += "," + sql;
}
/**
* 扩展查询的前缀
* @param sql 添加的Sql
*/
public void appendSelectPagePrefix(String sql){
this.selectPrefixForPage += "," + sql;
}
public String getWhereSql() {
if(StringUtils.isBlank(this.whereSql)){
this.whereSql = " 1 = 1 ";
}
if(this.pageHelper!=null&& this.pageHelper.getLimit()>0){
return this.whereSql + (this.orderSql== null?"":this.orderSql) + (this.whereSubfixForPage == null?"":this.whereSubfixForPage);
}
return (StringUtils.isNotBlank(whereSql)?whereSql:" 1= 1 ") + (this.orderSql == null?"":this.orderSql);
}
/**
* 集合的查询封装为
* @param key 属性
* @param list 值
*/
public void wrapperForCollection(String key,Collection list){
if(!CollectionUtils.isEmpty(list)) {
removeQueryMap(key);
//不用in查询
StringBuffer sb = new StringBuffer();
sb.append("(");
list.stream().forEach(s -> {
sb.append(" ").append(getTableNick()).append(".").append(key).append(" = '").append(s).append("' or");
});
addCustomSql(key, sb.substring(0,sb.length()-2) +" )");
}
}
public void setWhereSql(String whereSql) {
this.whereSql = whereSql;
}
public Map getValuesMap() {
return valuesMap;
}
public void setValuesMap(Map valuesMap) {
this.valuesMap = valuesMap;
}
public String getTableNick() {
return tableNick;
}
public void setTableNick(String tableNick) {
this.tableNick = tableNick;
}
public String getOrderSql() {
return orderSql;
}
public void setOrderSql(String orderSql) {
this.orderSql = orderSql;
}
public String getOidFieldName() {
return oidFieldName;
}
public void setOidFieldName(String oidFieldName) {
this.oidFieldName = oidFieldName;
}
public VciQueryWrapperOption getQueryWrapperOption() {
return queryWrapperOption;
}
public void setQueryWrapperOption(VciQueryWrapperOption queryWrapperOption) {
this.queryWrapperOption = queryWrapperOption;
}
public boolean isDistinct() {
return distinct;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public Map getCustomerSqlMap() {
return customerSqlMap;
}
public void setCustomerSqlMap(Map customerSqlMap) {
this.customerSqlMap = customerSqlMap;
}
@Override
public String toString() {
return "VciQueryWrapperForDO{" +
"conditionMap=" + conditionMap +
", customerSqlMap=" + customerSqlMap +
", oidFieldName='" + oidFieldName + '\'' +
", queryWrapperOption=" + queryWrapperOption +
", doClass=" + doClass +
", pageHelper=" + pageHelper +
", allFieldNameMap=" + allFieldNameMap +
", xmlTypeFieldList=" + xmlTypeFieldList +
", distinct=" + distinct +
", allFieldTypeMap=" + allFieldTypeMap +
", referFieldInfoList=" + referFieldInfoList +
", useReferMap=" + useReferMap +
", enumFieldMap=" + enumFieldMap +
", linkTableSql='" + linkTableSql + '\'' +
", selectFieldSql='" + selectFieldSql + '\'' +
", selectPrefixForPage='" + selectPrefixForPage + '\'' +
", whereSql='" + whereSql + '\'' +
", orderSql='" + orderSql + '\'' +
", whereSubfixForPage='" + whereSubfixForPage + '\'' +
", valuesMap=" + valuesMap +
", tableNick='" + tableNick + '\'' +
'}';
}
}