获取索引信息
1.核心思路
通过以下sql语句,例如对于user表
show index from user
执行结果如下:
2.实现
连接数据库后执行sql语句,我们重点关注下图标注的三个熟悉
代码如下:
PreparedStatement ps = null;ResultSet fieldResult = null;List<FieldInfo> fieldInfoList = new ArrayList<>();try {ps = conn.prepareStatement(String.format(SQL_SHOW_FIELDS_INDEX, tableInfo.getTableName()));fieldResult = ps.executeQuery();while (fieldResult.next()) {String key_name = fieldResult.getString("Key_name");String column_name = fieldResult.getString("Column_name");int non_unique = fieldResult.getInt("Non_unique");
}
}
如果unique属性为1,表示该索引不是唯一索引,我们更在意唯一索引,所以该字段跳过
if(non_unique==1){continue;}
之后,我们从tableinfo中拿到存储索引名称与对应的字段信息列表fieldinfos的map,根据索引名称获取列表,如果列表不存在,创建列表,然后将column名称所对应的字段信息对象fieldinfo存到列表中去
List<FieldInfo> fieldInfos = tableInfo.getKeyIndexMap().get(key_name);if(null==fieldInfos){fieldInfos = new ArrayList<>();tableInfo.getKeyIndexMap().put(key_name,fieldInfos);}for (FieldInfo fieldInfo : tableInfo.getFieldList()) {if(fieldInfo.getFieldName().equals(column_name)){fieldInfos.add(fieldInfo);}}
获取索引信息函数的完整代码如下:
/*** 获取表唯一索引信息* @author nangong* @dateTime 2024/11/21 14:33* @param tableInfo*/private static void getKeyIndexInfo(TableInfo tableInfo) {PreparedStatement ps = null;ResultSet fieldResult = null;List<FieldInfo> fieldInfoList = new ArrayList<>();try {ps = conn.prepareStatement(String.format(SQL_SHOW_FIELDS_INDEX, tableInfo.getTableName()));fieldResult = ps.executeQuery();while (fieldResult.next()) {String key_name = fieldResult.getString("Key_name");String column_name = fieldResult.getString("Column_name");int non_unique = fieldResult.getInt("Non_unique");if(non_unique==1){continue;}List<FieldInfo> fieldInfos = tableInfo.getKeyIndexMap().get(key_name);if(null==fieldInfos){fieldInfos = new ArrayList<>();tableInfo.getKeyIndexMap().put(key_name,fieldInfos);}for (FieldInfo fieldInfo : tableInfo.getFieldList()) {if(fieldInfo.getFieldName().equals(column_name)){fieldInfos.add(fieldInfo);}}}} catch (Exception e) {logger.error("读取索引失败", e);} finally {if (fieldResult != null) {try {fieldResult.close();} catch (SQLException e) {e.printStackTrace();}}if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}}}}
然后在设置tableinfo熟悉那里调用该函数即可
致此,获取表的所有信息就完成了,之后就是针对表的信息生成po类,三层架构中的各种方法等等