提交 d02b152d authored 作者: HASEE's avatar HASEE

model layer 扫描所有主系统Entity

上级 903a1460
......@@ -26,6 +26,9 @@ import java.util.Map;
public class ModelController {
@Autowired
private ModelService modelService;
@Autowired
private ClassLoader classLoader;
/**
* @Author WWW
* @Description 得到所有数据库信息
......@@ -95,4 +98,10 @@ public class ModelController {
return i;
}
@GetMapping("/getPackge")
public String testPack(){
String name = this.getClass().getPackage().getName();
return name;
}
}
......@@ -11,7 +11,7 @@ import lombok.Data;
* @Date 2021/3/1 9:58
* @Version 1.0
*/
@WorkFlowCoreNoScan
@Data
public class ColumnVO {
......
......@@ -13,7 +13,6 @@ import java.util.List;
* @Date 2021/3/1 9:56
* @Version 1.0
*/
@WorkFlowCoreNoScan
@Data
public class TableVO {
......
......@@ -12,42 +12,26 @@ import com.tykj.workflowcore.model_layer.model.TableVO;
import com.tykj.workflowcore.model_layer.service.ModelService;
import com.tykj.workflowcore.model_layer.utils.CreatTableUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.internal.SessionImpl;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.TimestampType;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import javax.xml.crypto.Data;
import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
......@@ -62,7 +46,6 @@ import java.util.stream.Collectors;
public class ModelImpl implements ModelService {
@Autowired
private EntityManagerFactory entityManagerFactory;
......@@ -72,14 +55,26 @@ public class ModelImpl implements ModelService {
@Autowired
private ColumnInfoDao columnInfoDao;
/**
* @param
* @return java.util.List<com.tykj.workflowcore.model_layer.model.TableInfo>
* @Author WWW
* @Description 得到所有表
* @Date 16:14 2021/3/5
**/
@Override
public List<TableInfo> ListAllEntities() {
List<TableInfo> all = tableInfoDao.findAll();
return all;
}
/**
* @param TableName
* @return java.util.List<com.tykj.workflowcore.model_layer.model.ColumnInfo>
* @Author WWW
* @Description 根据表名得到所有字段名
* @Date 16:15 2021/3/5
**/
@Override
public List<ColumnInfo> showModelFields(String TableName) {
......@@ -93,6 +88,13 @@ public class ModelImpl implements ModelService {
return all;
}
/**
* @param jsonStr
* @return com.tykj.workflowcore.model_layer.model.TableVO
* @Author WWW
* @Description 将json字符串转换实体类
* @Date 16:15 2021/3/5
**/
@Override
public TableVO addModel(String jsonStr) {
ObjectMapper mapper = new ObjectMapper();
......@@ -105,12 +107,19 @@ public class ModelImpl implements ModelService {
return tableVO;
}
/**
* @param tableVO
* @return com.tykj.workflowcore.model_layer.model.TableVO
* @Author WWW
* @Description 新建一张表
* @Date 16:16 2021/3/5
**/
@Override
public TableVO NewTable(TableVO tableVO) {
String XML_MAPPING = CreatTableUtil.CreatTable(tableVO);
CreatTableUtil creatTableUtil = new CreatTableUtil();
Session session = creatTableUtil.getSession(entityManagerFactory,XML_MAPPING);
CreatTableUtil creatTableUtil = new CreatTableUtil();
Session session = creatTableUtil.getSession(entityManagerFactory, XML_MAPPING);
List<ColumnVO> dataList = tableVO.getDataList();
......@@ -139,10 +148,17 @@ public class ModelImpl implements ModelService {
return tableVO;
}
/**
* @param map
* @return int
* @Author WWW
* @Description 根据表名新增数据
* @Date 16:17 2021/3/5
**/
@Override
public int putValueByEntityName(Map<String, Object> map) {
for (String tableName:
map.keySet()) {
for (String tableName :
map.keySet()) {
//查找对应的表
Specification spec = (Specification) (root, criteriaQuery, criteriaBuilder) -> {
Predicate equal = null;
......@@ -152,28 +168,37 @@ public class ModelImpl implements ModelService {
};
Optional one = tableInfoDao.findOne(spec);
TableInfo tableInfo = null;
if (one.isPresent()){
if (one.isPresent()) {
tableInfo = (TableInfo) one.get();
}
Object values = map.get(tableName);
if (values instanceof Map){
if (values instanceof Map) {
//插入数据
insertValue(tableInfo.getName(),tableInfo.getXML(), (Map) values);
}else {
insertValue(tableInfo.getName(), tableInfo.getXML(), (Map) values);
} else {
//循环插入数据
List valuesList = (List) values;
for (int i = 0; i < valuesList.size(); i++) {
insertValue(tableInfo.getName(),tableInfo.getXML(), (Map) valuesList.get(i));
insertValue(tableInfo.getName(), tableInfo.getXML(), (Map) valuesList.get(i));
}
}
}
return 0;
}
public void insertValue(String tableName,String xml,Map map){
CreatTableUtil creatTableUtil = new CreatTableUtil();
Session newSession = creatTableUtil.getSession(entityManagerFactory,xml);
/**
* @param tableName
* @param xml
* @param map
* @return void
* @Author WWW
* @Description 新增参数的方法
* @Date 16:17 2021/3/5
**/
public void insertValue(String tableName, String xml, Map map) {
CreatTableUtil creatTableUtil = new CreatTableUtil();
Session newSession = creatTableUtil.getSession(entityManagerFactory, xml);
SessionImpl session = (SessionImpl) newSession;
EntityPersister entityPersister = session.getEntityPersister(tableName, map);
Type[] propertyTypes = entityPersister.getPropertyTypes();
......@@ -183,25 +208,27 @@ public class ModelImpl implements ModelService {
Object value = propertyValuesToInsert[i];
Type propertyType = propertyTypes[i];
//先将Type转为java类
if (propertyType instanceof TimestampType){
if (propertyType instanceof TimestampType) {
try {
Date parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((String) value);
map.put(propertyNames[i],parse);
map.put(propertyNames[i], parse);
} catch (ParseException e) {
e.printStackTrace(); }
e.printStackTrace();
}
}
if (propertyType instanceof IntegerType){
if (propertyType instanceof IntegerType) {
//然后调用强转方法
int i1 = Integer.parseInt(propertyNames[i]);
map.put(propertyNames[i],i1);
map.put(propertyNames[i], i1);
}
if (propertyType instanceof StringType){
//然后调用强转方法
propertyNames[i]=propertyNames[i]+"";
map.put(propertyNames[i],propertyNames[i]);
if (propertyType instanceof StringType) {
//然后调用强转方法
propertyNames[i] = propertyNames[i] + "";
map.put(propertyNames[i], propertyNames[i]);
}
}
newSession.saveOrUpdate(tableName,map);
newSession.saveOrUpdate(tableName, map);
newSession.close();
}
}
......@@ -7,10 +7,7 @@ import java.io.FileFilter;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
......@@ -22,179 +19,42 @@ import java.util.jar.JarFile;
* @Version 1.0
*/
public class ClassScanUtil {
// /**
// * 扫描给定的基包下的所有的类(包括子包)。
// * @param basePackageName 基包的名称
// * @return 所有在基包下的类的全名
// */
// public static Set<String> scanBasePackage(String basePackageName){
// String packageDirName = basePackageName.replace(".", "/");
// URL url = Thread.currentThread().getContextClassLoader().getResource(packageDirName);
// System.out.println(url);
// File targetFile = new File(url.getFile());
// if(!targetFile.exists() || targetFile.isFile()){
// throw new RuntimeException(basePackageName + "不是一个包名或者该包名不存在");
// }
// Set<String> classNames = new HashSet<String>();
// getAllClass(targetFile, basePackageName, classNames);
// return classNames;
//
// }
/**
* 得到所有在parentFile目录下的class文件名称
* @param parentFile
* @param classNames
* @param basePackageName
*/
private static void getAllClass(File parentFile, String basePackageName, Set<String> classNames){
File[] files = parentFile.listFiles();
for(File file : files){
String path = file.getPath();
if(file.isFile()){
if(path.endsWith(".class")){
classNames.add(
basePackageName + "." +
path.substring(
path.lastIndexOf('\\') + 1, path.lastIndexOf('.')
)
);
}
}else{
basePackageName = basePackageName + path.substring(path.lastIndexOf('\\') + 1);
getAllClass(file, basePackageName, classNames);
private void loadClassByPath(String root, String path, List<Class<?>> list, ClassLoader load) {
File f = new File(path);
if (root == null) root = f.getPath();
//判断是否是class文件
if (f.isFile() && f.getName().matches("^.*\\.class$")) {
try {
String classPath = f.getPath();
//截取出className 将路径分割符替换为.(windows是\ linux、mac是/)
String className = classPath.substring(root.length() + 1, classPath.length() - 6).replace('/', '.').replace('\\', '.');
list.add(load.loadClass(className));
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
File[] fs = f.listFiles();
if (fs == null) return;
for (File file : fs) {
loadClassByPath(root, file.getPath(), list, load);
}
}
}
public static Set<Class<?>> getClasses(String pack){
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try{
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()){
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
}else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try{
// 获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()){
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
System.out.println(packageName+"666666666666");
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try{
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
}catch (ClassNotFoundException e){
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
}catch (IOException e){
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
public List<Class<?>> loadClassByLoader(ClassLoader load) {
List<Class<?>> classes = new ArrayList<>();
try {
Enumeration<URL> urls = load.getResources("");
//放所有类型
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
//文件类型(其实是文件夹)
if (url.getProtocol().equals("file")) {
loadClassByPath(null, url.getPath(), classes, load);
}
}
}catch (IOException e){
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(
String packageName,
String packagePath,
final boolean recursive,
Set<Class<?>> classes){
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
File[] dirfiles = dir.listFiles(file -> (recursive && file.isDirectory()) || (file.getName().endsWith(".class")));
// 循环所有文件
for (File file : dirfiles){
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
}else{
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try{
// 添加到集合中去
// classes.add(Class.forName(packageName + '.' +
// className));
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
}catch (ClassNotFoundException e){
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
package com.tykj.workflowcore.model_layer.utils;
import com.tykj.workflowcore.model_layer.annotatiion.WorkFlowCoreNoScan;
import com.tykj.workflowcore.model_layer.model.ColumnVO;
import com.tykj.workflowcore.model_layer.model.TableInfo;
import com.tykj.workflowcore.model_layer.model.TableVO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
......@@ -11,8 +15,12 @@ import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.hibernate.tool.schema.TargetType;
import javax.persistence.Entity;
import javax.persistence.EntityManagerFactory;
import java.io.ByteArrayInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
......@@ -23,13 +31,8 @@ import java.util.List;
* @Date 2021/3/1 14:35
* @Version 1.0
*/
public class CreatTableUtil {
public static String CreatTable(TableVO tableVO){
List<ColumnVO> dataList = tableVO.getDataList();
String XML_MAPPING = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE hibernate-mapping PUBLIC\n" +
......@@ -47,7 +50,6 @@ public class CreatTableUtil {
"\" column=\"" + columnVO.getFieldName() + "\"/>\n";
}
XML_MAPPING += " </class>" +
"</hibernate-mapping>";
......@@ -75,4 +77,80 @@ public class CreatTableUtil {
return newSession;
}
public TableInfo SwaggerScan(Class<?> aClass) {
TableInfo tableInfo = null;
if (!aClass.isAnnotationPresent(WorkFlowCoreNoScan.class)){
if (aClass.isAnnotationPresent(Entity.class)) {
tableInfo =new TableInfo();
TableVO tableVO=new TableVO();
String className = getClassName(aClass.toString());
tableVO.setModelName(className.toLowerCase()+"_ModelTest");
if (aClass.isAnnotationPresent(ApiModel.class)) {
ApiModel annotation = aClass.getAnnotation(ApiModel.class);
StringBuilder APiModelDocument = new StringBuilder();
if (annotation.value() != null && !annotation.value().equals("")) {
APiModelDocument.append( annotation.value()+ "|");
}
if (annotation.description() != null && !annotation.description().equals("")) {
APiModelDocument.append( annotation.description() + "|");
}
tableVO.setModelTitle(APiModelDocument.toString());
}
else {
tableVO.setModelTitle("");
}
Field[] declaredFields = aClass.getDeclaredFields();
List<ColumnVO> list=new ArrayList<>();
for (Field declaredField : declaredFields) {
ColumnVO columnVO=new ColumnVO();
Type genericType = declaredField.getGenericType();
columnVO.setFiledType(genericType.toString());
columnVO.setFieldName(getClassName(declaredField.toString()));
if (declaredField.isAnnotationPresent(ApiModelProperty.class)) {
ApiModelProperty annotation = declaredField.getAnnotation(ApiModelProperty.class);
StringBuilder ApiModelPropertyDocument = new StringBuilder();
if (annotation.value() != null && !annotation.value().equals("")) {
ApiModelPropertyDocument.append( annotation.value() + "|");
}
if (annotation.example() != null && !annotation.example().equals("")) {
ApiModelPropertyDocument.append( annotation.example() + "|");
}
columnVO.setFiledDescription(ApiModelPropertyDocument.toString());
}
else {
columnVO.setFiledDescription("无描述");
}
list.add(columnVO);
}
tableVO.setDataList(list);
String xml = CreatTable(tableVO);
tableInfo.setName(tableVO.getModelName());
tableInfo.setCnName(tableVO.getModelTitle());
tableInfo.setXML(xml);
}
}
return tableInfo;
}
public static String getClassName(String aClass){
int i = aClass.lastIndexOf(".");
String substring = aClass.substring(i+1);
return substring;
}
}
package com.tykj.workflowcore.model_layer.utils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Entity;
import java.lang.reflect.Field;
/**
* @ClassName JugdeSwagger
* @Description TODO
* @Author WWW
* @Date 2021/2/26 9:53
* @Version 1.0
*/
public class SwaggerUtil {
public static void Swagger(Class<?> aClass) {
if (aClass.isAnnotationPresent(Entity.class)) {
if (aClass.isAnnotationPresent(ApiModel.class)) {
ApiModel annotation = aClass.getAnnotation(ApiModel.class);
StringBuilder APiModelDocument = new StringBuilder();
if (annotation.value() != null && !annotation.value().equals("")) {
APiModelDocument.append(aClass + "的文档:value=" + annotation.value().toString() + ".");
}
if (annotation.description() != null && !annotation.description().equals("")) {
APiModelDocument.append("description=" + annotation.description().toString() + ".");
}
System.out.println(APiModelDocument.toString());
}
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
if (declaredField.isAnnotationPresent(ApiModelProperty.class)) {
ApiModelProperty annotation = declaredField.getAnnotation(ApiModelProperty.class);
StringBuilder ApiModelPropertyDocument = new StringBuilder();
if (annotation.value() != null && !annotation.value().equals("")) {
// System.out.println(declaredField+"的文档是"+annotation.value());
ApiModelPropertyDocument.append(declaredField + "的文档:value=" + annotation.value() + ".");
}
if (annotation.example() != null && !annotation.example().equals("")) {
// System.out.println(declaredField+"的文档是"+annotation.value());
ApiModelPropertyDocument.append("example=" + annotation.example() + ".");
}
System.out.println(ApiModelPropertyDocument.toString());
}
}
}
}
public static boolean isSwagger(Class<?> aClass) {
if (aClass.isAnnotationPresent(Entity.class)) {
if (aClass.isAnnotationPresent(ApiModel.class)) {
return true;
}
}
return false;
}
}
......@@ -5,8 +5,6 @@ spring:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/model_layer?serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=true
type: com.alibaba.druid.pool.DruidDataSource
jpa:
hibernate:
......@@ -15,15 +13,5 @@ spring:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
spring:
datasource:
username: root
password: Huang123+
url: jdbc:mysql://47.106.142.73:3306/www?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8&nullCatalogMeansCurrent=true
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
show-sql: true
hibernate:
ddl-auto: update
\ No newline at end of file
server:
port: 8900
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论