由于大多数数据库将这些约束作为索引存储,因此您可以像先前提到的那样使用
DatabaseMetaData.getIndexInfo()。在我使用
Postgresql时,这很有效。
只有在文档中说明时,才需要使用第4个参数true来调用
getIndexInfo()
:
unique
- 当为true时,仅返回唯一值的索引;当为false时,返回无论是否唯一的索引
使用以下代码:
public static class UniqueConstraint {
public String table;
public String name;
public List<String> columns = new ArrayList<>();
public String toString() {
return String.format("[%s] %s: %s", table, name, columns);
}
}
public static List<UniqueConstraint> getUniqueConstraints(Connection conn, String schema, String table) throws SQLException {
Map<String, UniqueConstraint> constraints = new HashMap<>();
DatabaseMetaData dm = conn.getMetaData();
ResultSet rs = dm.getIndexInfo(null, schema, table, true, true);
while(rs.next()) {
String indexName = rs.getString("index_name");
String columnName = rs.getString("column_name");
UniqueConstraint constraint = new UniqueConstraint();
constraint.table = table;
constraint.name = indexName;
constraint.columns.add(columnName);
constraints.compute(indexName, (key, value) -> {
if (value == null) { return constraint; }
value.columns.add(columnName);
return value;
});
}
return new ArrayList<>(constraints.values());
}
你可以调用:
getUniqueConstraints(conn, "public", tableName);
获取给定表的所有唯一约束条件列表。由于一个索引可以覆盖多个列,如果它们仅在组合中是唯一的,则将约束条件分组。