提交 8d5f5e0f authored 作者: 黄夏豪's avatar 黄夏豪

[数据模型] 修改了复杂查询的逻辑

上级 73ab797c
package com.tykj.model_layer.controller; package com.tykj.model_layer.controller;
import com.tykj.base.result.ResultUtil; import com.tykj.base.result.ResultUtil;
import com.tykj.model_layer.entity.TableInfo; import com.tykj.model_layer.entity.TableInfo;
import com.tykj.model_layer.entity.vo.*; import com.tykj.model_layer.entity.vo.*;
...@@ -79,10 +78,9 @@ public class ModelController { ...@@ -79,10 +78,9 @@ public class ModelController {
SearchTableInfoVo searchTableInfoVo = new SearchTableInfoVo(); SearchTableInfoVo searchTableInfoVo = new SearchTableInfoVo();
searchTableInfoVo.setModelName(tableVO.getModelName()); searchTableInfoVo.setModelName(tableVO.getModelName());
List<TableInfo> tableInfos = modelService.listAllEntities(searchTableInfoVo); List<TableInfo> tableInfos = modelService.listAllEntities(searchTableInfoVo);
if (tableInfos.size()>0){ if (tableInfos.size() > 0) {
return ResultUtil.failed("表已经存在!"); return ResultUtil.failed("表已经存在!");
} }
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
modelService.newTable(tableVO); modelService.newTable(tableVO);
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
...@@ -108,7 +106,24 @@ public class ModelController { ...@@ -108,7 +106,24 @@ public class ModelController {
return ResultUtil.success("", "数据插入成功!"); return ResultUtil.success("", "数据插入成功!");
} }
return ResultUtil.failed("模型类型不支持插入数据!"); return ResultUtil.failed("模型类型不支持插入数据!");
}
/**
* @param mapList
* @return int
* @Author WWW
* @Description 对应表插入数据
* map (表名,字段数据)
* @Date 16:22 2021/3/4
**/
@ApiOperation(value = "根据表名表插入数据")
@PostMapping("/insertValueList")
public ResponseEntity insertValueList(@RequestBody List<Map<String, Object>> mapList) {
int i = modelService.putValueByEntityNameList(mapList);
if (i == 0) {
return ResultUtil.success("", "数据插入成功!");
}
return ResultUtil.failed("模型类型不支持插入数据!");
} }
/** /**
...@@ -130,18 +145,27 @@ public class ModelController { ...@@ -130,18 +145,27 @@ public class ModelController {
} }
/** /**
* @param tableName * @param complexQueryVo
* @param queryConditions * @return 复杂查询
* @return org.springframework.http.ResponseEntity */
* @Author WWW
* @Description 复杂查询
* @Date 11:03 2021/3/11
**/
@ApiOperation("复杂查询") @ApiOperation("复杂查询")
@GetMapping("/complexQuery") @PostMapping("/complexQuery")
public ResponseEntity complexQuery(@RequestParam(value = "tableName")String tableName, public ResponseEntity complexQuery(@RequestBody complexQueryVo complexQueryVo) {
@RequestParam(value = "queryConditions" ,required=false) List<QueryCondition> queryConditions) { List list = modelService.complexQuery(complexQueryVo.getTableName(), complexQueryVo.getColumnNames(), complexQueryVo.getQueryConditions());
List list = modelService.complexQuery(tableName, queryConditions); if (list != null) {
return ResultUtil.success(list, "查询成功!");
}
return ResultUtil.failed(null, "没有数据!");
}
/**
* @param complexQueryVo
* @return 复杂查询
*/
@ApiOperation("复杂查询(分类)")
@PostMapping("/complexQuery/group")
public ResponseEntity complexQueryWithGroup(@RequestBody complexQueryVo complexQueryVo) {
Map<Object, List<Map<String, Object>>> list = modelService.complexQueryWithGroup(complexQueryVo.getTableName(), complexQueryVo.getColumnNames(), complexQueryVo.getQueryConditions(), complexQueryVo.getGroupByColumn());
if (list != null) { if (list != null) {
return ResultUtil.success(list, "查询成功!"); return ResultUtil.success(list, "查询成功!");
} }
...@@ -180,9 +204,9 @@ public class ModelController { ...@@ -180,9 +204,9 @@ public class ModelController {
@ApiOperation("自定义SQL查询") @ApiOperation("自定义SQL查询")
@PostMapping("/sql") @PostMapping("/sql")
public ResponseEntity executeSql(String sql){ public ResponseEntity executeSql(String sql) {
try { try {
return ResultUtil.success(modelService.executeQuery(sql),"查询成功!"); return ResultUtil.success(modelService.executeQuery(sql), "查询成功!");
} catch (SQLException throwables) { } catch (SQLException throwables) {
throwables.printStackTrace(); throwables.printStackTrace();
} }
......
...@@ -8,6 +8,7 @@ import com.tykj.model_layer.entity.ColumnInfo; ...@@ -8,6 +8,7 @@ import com.tykj.model_layer.entity.ColumnInfo;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
......
package com.tykj.model_layer.entity.vo;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.Map;
/**
* @author HuangXiahao
* @version V1.0
* @class InsertListVo
* @packageName com.tykj.model_layer.entity.vo
**/
@AllArgsConstructor
@NoArgsConstructor
@Data
@ApiModel("删除VO类")
public class InsertListVo {
List<Map<String, Object>> mapList;
}
package com.tykj.model_layer.entity.vo; package com.tykj.model_layer.entity.vo;
import com.tykj.model_layer.entity.customEnums.ConnectionType;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
...@@ -33,4 +34,7 @@ public class QueryCondition { ...@@ -33,4 +34,7 @@ public class QueryCondition {
@ApiModelProperty(value = "条件参数值",example = "18") @ApiModelProperty(value = "条件参数值",example = "18")
private String value; private String value;
@ApiModelProperty(value = "连接条件",example = "or或者and")
private ConnectionType connectionType;
} }
package com.tykj.model_layer.entity.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author HuangXiahao
* @version V1.0
* @class complexQueryVo
* @packageName com.tykj.model_layer.entity.vo
**/
@ApiModel("复杂查询VO")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class complexQueryVo {
@ApiModelProperty("表名")
String tableName;
@ApiModelProperty("筛选字段")
List<String> columnNames;
@ApiModelProperty("查询条件")
List<QueryCondition> queryConditions;
@ApiModelProperty("分类字段")
String groupByColumn;
}
...@@ -61,6 +61,13 @@ public interface ModelService { ...@@ -61,6 +61,13 @@ public interface ModelService {
*/ */
int putValueByEntityName(Map<String, Object> map); int putValueByEntityName(Map<String, Object> map);
/**
* 插入一组数据
* @param mapList
* @return
*/
public int putValueByEntityNameList(List<Map<String, Object>> mapList);
/** /**
...@@ -78,7 +85,15 @@ public interface ModelService { ...@@ -78,7 +85,15 @@ public interface ModelService {
* @param queryConditions * @param queryConditions
* @return * @return
*/ */
List<Map<String, Object>> complexQuery(String tableName, List<QueryCondition> queryConditions); List<Map<String, Object>> complexQuery(String tableName,List<String> columnNames, List<QueryCondition> queryConditions);
/**
* 复杂查询(带分类)
* @param tableName
* @param queryConditions
* @return
*/
Map<Object,List<Map<String, Object>>> complexQueryWithGroup(String tableName,List<String> columnNames, List<QueryCondition> queryConditions,String groupByColumn);
/** /**
......
package com.tykj.model_layer.service.impl; package com.tykj.model_layer.service.impl;
import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.github.wenhao.jpa.PredicateBuilder; import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications; import com.github.wenhao.jpa.Specifications;
import com.google.common.base.Strings;
import com.tykj.base.result.ApiException; import com.tykj.base.result.ApiException;
import com.tykj.model_layer.dao.ColumnInfoDao; import com.tykj.model_layer.dao.ColumnInfoDao;
...@@ -14,6 +14,7 @@ import com.tykj.model_layer.entity.TableInfo; ...@@ -14,6 +14,7 @@ import com.tykj.model_layer.entity.TableInfo;
import com.tykj.model_layer.entity.vo.*; import com.tykj.model_layer.entity.vo.*;
import com.tykj.model_layer.myEnum.ModelType; import com.tykj.model_layer.myEnum.ModelType;
import com.tykj.model_layer.service.ModelService; import com.tykj.model_layer.service.ModelService;
import com.tykj.model_layer.utils.ObjectUtil;
import com.tykj.model_layer.utils.SessionUtil; import com.tykj.model_layer.utils.SessionUtil;
import com.tykj.model_layer.utils.SqlUtil; import com.tykj.model_layer.utils.SqlUtil;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
...@@ -21,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; ...@@ -21,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.hibernate.Session; import org.hibernate.Session;
import org.hibernate.internal.SessionImpl; import org.hibernate.internal.SessionImpl;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
...@@ -29,6 +31,7 @@ import org.hibernate.type.IntegerType; ...@@ -29,6 +31,7 @@ import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType; import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType; import org.hibernate.type.TimestampType;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
...@@ -147,7 +150,6 @@ public class ModelImpl implements ModelService { ...@@ -147,7 +150,6 @@ public class ModelImpl implements ModelService {
} }
sessionUtil.addXml(xmlMapping); sessionUtil.addXml(xmlMapping);
Session session = sessionUtil.getSession(); Session session = sessionUtil.getSession();
List<ColumnVO> dataList = tableVO.getDataList(); List<ColumnVO> dataList = tableVO.getDataList();
List<String> collect = tableInfoDao.findAll() List<String> collect = tableInfoDao.findAll()
.stream() .stream()
...@@ -215,23 +217,81 @@ public class ModelImpl implements ModelService { ...@@ -215,23 +217,81 @@ public class ModelImpl implements ModelService {
tableInfo = (TableInfo) one.get(); tableInfo = (TableInfo) one.get();
} }
Integer modelType = tableInfo.getModelType(); Integer modelType = tableInfo.getModelType();
SessionImpl session = (SessionImpl)sessionUtil.getSession();
if (modelType.equals(ModelType.VIRTUAL)) { if (modelType.equals(ModelType.VIRTUAL)) {
Object values = map.get(tableName); Object values = map.get(tableName);
if (values instanceof Map) { if (values instanceof Map) {
//插入数据 //插入数据
insertValue(tableInfo.getModelName(), (Map) values); insertValue(tableInfo.getModelName(), (Map) values,session);
} else { } else {
//循环插入数据 //循环插入数据
List valuesList = (List) values; List valuesList = (List) values;
for (int i = 0; i < valuesList.size(); i++) { for (int i = 0; i < valuesList.size(); i++) {
insertValue(tableInfo.getModelName(), (Map) valuesList.get(i)); insertValue(tableInfo.getModelName(), (Map) valuesList.get(i),session);
} }
} }
session.saveOrUpdate(tableName, map);
session.getTransaction().begin();
session.getTransaction().commit();
session.close();
} else { } else {
return 1; return 1;
} }
}
return 0;
}
/**
* @param map
* @return int
* @Author WWW
* @Description 根据表名新增数据
* @Date 16:17 2021/3/5
**/
@Override
public int putValueByEntityNameList(List<Map<String, Object>> mapList) {
SessionImpl session = (SessionImpl)sessionUtil.getSession();
for (Map<String, Object> map : mapList) {
for (String tableName :
map.keySet()) {
//查找对应的表
Specification spec = (root, criteriaQuery, criteriaBuilder) -> {
Predicate equal;
Path name = root.get("modelName");
equal = criteriaBuilder.equal(name, tableName);
return equal;
};
Optional one = tableInfoDao.findOne(spec);
TableInfo tableInfo = null;
if (one.isPresent()) {
tableInfo = (TableInfo) one.get();
}
Integer modelType = tableInfo.getModelType();
if (modelType.equals(ModelType.VIRTUAL)) {
Object values = map.get(tableName);
if (values instanceof Map) {
//插入数据
insertValue(tableInfo.getModelName(), (Map) values,session);
} else {
//循环插入数据
List valuesList = (List) values;
for (int i = 0; i < valuesList.size(); i++) {
insertValue(tableInfo.getModelName(), (Map) valuesList.get(i),session);
}
} }
session.saveOrUpdate(tableName, map);
} else {
return 1;
}
}
}
session.getTransaction().begin();
session.getTransaction().commit();
session.close();
return 0; return 0;
} }
...@@ -243,9 +303,7 @@ public class ModelImpl implements ModelService { ...@@ -243,9 +303,7 @@ public class ModelImpl implements ModelService {
* @Description 新增参数的方法 * @Description 新增参数的方法
* @Date 16:17 2021/3/5 * @Date 16:17 2021/3/5
**/ **/
public void insertValue(String tableName, Map map) { public void insertValue(String tableName, Map map,SessionImpl session) {
Session newSession = sessionUtil.getSession();
SessionImpl session = (SessionImpl) newSession;
EntityPersister entityPersister = session.getEntityPersister(tableName, map); EntityPersister entityPersister = session.getEntityPersister(tableName, map);
Type[] propertyTypes = entityPersister.getPropertyTypes(); Type[] propertyTypes = entityPersister.getPropertyTypes();
String[] propertyNames = entityPersister.getEntityPersister().getPropertyNames(); String[] propertyNames = entityPersister.getEntityPersister().getPropertyNames();
...@@ -273,10 +331,7 @@ public class ModelImpl implements ModelService { ...@@ -273,10 +331,7 @@ public class ModelImpl implements ModelService {
map.put(propertyNames[i], value); map.put(propertyNames[i], value);
} }
} }
newSession.saveOrUpdate(tableName, map);
newSession.getTransaction().begin();
newSession.getTransaction().commit();
newSession.close();
} }
...@@ -318,19 +373,39 @@ public class ModelImpl implements ModelService { ...@@ -318,19 +373,39 @@ public class ModelImpl implements ModelService {
} }
@Override @Override
public List<Map<String, Object>> complexQuery(String tableName, List<QueryCondition> queryConditions) { public List<Map<String, Object>> complexQuery(String tableName, List<String> columnNames, List<QueryCondition> queryConditions) {
if (Strings.isNotEmpty(tableName)) {
if (!"".equals(tableName)) { String query = createQuery(tableName, columnNames, queryConditions, Strings.EMPTY);
String query = createQuery(tableName, queryConditions);
Session session = sessionUtil.getSession(); Session session = sessionUtil.getSession();
Query query1 = session.createQuery(query); Query query1 = session.createQuery(query);
List<Map<String, Object>> list = query1.list(); List<Map<String, Object>> list = query1.list();
return list; return list;
} }
return null; return null;
} }
@Override
public Map<Object, List<Map<String, Object>>> complexQueryWithGroup(String tableName, List<String> columnNames, List<QueryCondition> queryConditions, String groupByColumn) {
Map<Object, List<Map<String, Object>>> result = new HashMap<>();
if (Strings.isNotEmpty(tableName)) {
String query = createQuery(tableName, new ArrayList<>(), queryConditions, Strings.EMPTY);
Session session = sessionUtil.getSession();
Query query1 = session.createQuery(query);
List<Map<String, Object>> list = query1.list();
if (Strings.isNotEmpty(groupByColumn)) {
Set<Object> groupValues = list.stream().map(obj -> obj.get(groupByColumn)).collect(Collectors.toSet());
for (Object groupValue : groupValues) {
List<Map<String, Object>> entityList = list.stream().filter(obj -> Objects.equals(obj.get(groupByColumn), groupValue)).collect(Collectors.toList());
result.put(groupValue, entityList);
}
} else {
result.put("all", list);
}
return result;
}
return null;
}
@Override @Override
public int updateTable(UpdateTableInfoVO updateTableInfoVO) { public int updateTable(UpdateTableInfoVO updateTableInfoVO) {
//tableInfo和columnInfo变化 //tableInfo和columnInfo变化
......
...@@ -2,6 +2,7 @@ package com.tykj.model_layer.utils; ...@@ -2,6 +2,7 @@ package com.tykj.model_layer.utils;
import com.tykj.model_layer.entity.vo.QueryCondition; import com.tykj.model_layer.entity.vo.QueryCondition;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
...@@ -12,20 +13,39 @@ import java.util.Objects; ...@@ -12,20 +13,39 @@ import java.util.Objects;
@Slf4j @Slf4j
public class HqlUtil { public class HqlUtil {
public static String createQuery(String tableName, List<QueryCondition> conditions) { public static String createQuery(String tableName, List<String> columnNames, List<QueryCondition> conditions, String groupByColumn) {
StringBuilder result = new StringBuilder("select entity from "); StringBuilder result = new StringBuilder("select ");
result.append(tableName).append(" entity "); if (Objects.isNull(columnNames) || columnNames.isEmpty()) {
result.append("entity ");
} else {
for (String columnName : columnNames) {
result.append("entity.").append(columnName).append(",");
}
result.delete(result.lastIndexOf(","),result.length() );
}
result.append(" from ").append(tableName).append(" entity ");
if (Objects.nonNull(conditions) && !conditions.isEmpty()) { if (Objects.nonNull(conditions) && !conditions.isEmpty()) {
result.append(" where "); result.append(" where ");
for (QueryCondition condition : conditions) { for (QueryCondition condition : conditions) {
result.append("entity.") result.append("entity.")
.append(condition.getName()) .append(condition.getName())
.append(condition.getType()) .append(" " + condition.getType() + " ")
.append("'")
.append(condition.getValue()) .append(condition.getValue())
.append(" and "); .append("'")
.append(condition.getConnectionType().getType());
} }
if (result.lastIndexOf(" and ") > -1) {
result.delete(result.lastIndexOf(" and "), result.length()); result.delete(result.lastIndexOf(" and "), result.length());
} }
if (result.lastIndexOf(" or ") > -1) {
result.delete(result.lastIndexOf(" or "), result.length());
}
}
if (StringUtils.isNotEmpty(groupByColumn)) {
result.append(" group by entity." + groupByColumn);
}
System.out.println(result.toString());
return result.toString(); return result.toString();
} }
......
package com.tykj.model_layer.utils;
import org.apache.logging.log4j.util.Strings;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author HuangXiahao
* @version V1.0
* @class ObjectUtil
* @packageName com.tykj.model_layer.utils
**/
public class ObjectUtil {
//Object转Map
public static Map<String, Object> objectToMap(Object obj) {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = null;
try {
value = field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
map.put(fieldName, value);
}
return map;
}
}
spring: spring:
datasource: datasource:
username: root username: root
password: 123456 password: Huang123+
url: jdbc:mysql://localhost:3306/data?useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf-8 url: jdbc:mysql://47.106.142.73:3306/dataTest?useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf-8&nullCatalogMeansCurrent=true
driver-class-name: com.mysql.cj.jdbc.Driver driver-class-name: com.mysql.cj.jdbc.Driver
jpa: jpa:
show-sql: true show-sql: true
hibernate: hibernate:
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论