hibernate根據包名獲取該包下實體類,資料庫中不存在的庫表名稱
阿新 • • 發佈:2020-07-31
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.supermap.realestate_bh.registration.util.StringUtil;
import com.supermap.wisdombusiness.core.SuperSpringContext;
import com.supermap.wisdombusiness_bh.framework.dao.impl.CommonDao;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate4.SessionFactoryUtils;
import javax.persistence.Table;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public static Set getTableNotExits(){try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String packagename = "com.supermap.realestate.registration.model";
packagename = "";
String packagePath = packagename.replaceAll("\\.", "\\/");
URL url = loader.getResource(packagePath);
String path = url.getPath();File file = new File(path);
File[] files = file.listFiles();
List list = new LinkedList<>();
Set<String> stringSet = new HashSet<>();
for (File file1 : files) {
if(file1.isDirectory()) continue;
String filename = file1.getName();
String name = packagename + "." + filename.replace(".class","");
System.out.println(name);
Class cl = Class.forName(name);
if(cl.isAnnotationPresent(Table.class)){
Table table = (Table)cl.getAnnotation(Table.class);
//指定資料庫/使用者
if("bdcdck".equalsIgnoreCase(table.schema())) stringSet.add(table.schema() + "&" + table.name());
}
list.add(packagename + "." + file1.getName());
}
SessionFactory object = SuperSpringContext.getContext().getBean(CommonDao.class).getSessionFactory();
Connection connection = SessionFactoryUtils.getDataSource(object).getConnection();
DatabaseMetaData databaseMetaData = connection.getMetaData();
Set<String> set = new HashSet<>();
for (String s : stringSet) {
if(StringUtil.isEmpty(s)) continue;
String[] ss = s.split("&");
ResultSet rs = databaseMetaData.getTables(null,ss[0].toUpperCase(),ss[1].toUpperCase(),new String[]{"TABLE"});
if(!rs.next()){
set.add(s);
}
}
return set;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}