1 获取数据库中所有表名
/**
* 获取所有表格
*
* @return
* @throws SQLException
*/
public List<String> getAllTableNames() {
List<String> list = new ArrayList<String>();
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Session session = sessionFactory.openSession();
if (session != null) {
list = session.doReturningWork(
connection -> {
List<String> resultList = new ArrayList<>();
ResultSet rs;
String username=connection.getMetaData().getUserName();
try {
rs = connection.getMetaData().getTables(connection.getCatalog(),username, null, null);
while (rs.next()) {
String table = rs.getObject(3).toString();
resultList.add(table);
}
} catch (SQLException e) {
//不存在
return resultList;
}
rs.close();
return resultList;
}
);
session.close();
}
return list;
}
2 判断数据库中某个表是否存在
/**
* 验证表是否存在
* @param tableName 表名
* @return (false:不存在,true:存在)
*/
public boolean checkTableNameExist(String tableName) {
List<String> tableNameList=getAllTableNames();
if(tableNameList==null||tableNameList.size()<=0){
return false;
}
return tableNameList.contains(tableName)?true:false;
}
3 返回数据库中存在的表名
/**
* 验证表是否存在
* @param tableNameList 需要判断的表名列表
* @return
*/
public List<String> getExistTableNameList(List<String> tableNameList) {
List<String> exsitableNameList=getAllTableNames();
if(exsitableNameList==null||exsitableNameList.size()<=0){
return new ArrayList<>();
}
return exsitableNameList.stream().filter(x->tableNameList.contains(x)).collect(Collectors.toList());
}