【问题标题】:Apache DdlUtils :: how to obtain the sequence name for auto-increment keys?Apache DdlUtils :: 如何获取自增键的序列名称?
【发布时间】:2012-08-05 00:09:50
【问题描述】:

我正在使用Apache DdlUtils 查询 PostgreSQL 数据库以获取表和列元数据(最终目标是自动生成 javax.persistence-annotated 实体 bean)。然而,在我看来,DdlUtils 库没有提供一种方法来获取自动增量列中使用的序列名称。 Column 类提供了一个 isAutoIncrement 方法来查询自动增量状态,但我找不到获取与其关联的序列名称的方法。这是 PostgreSQL 中 DDL 的一部分,例如:

orders=# \dS customer
                         Table "public.customer"
    Column     |       Type        |                    Modifiers
---------------+-------------------+--------------------------------------------------
 id            | integer           | not null default nextval('cst_id_seq'::regclass)
 name          | character varying | not null
 (...)

我应该直接查询一些元数据/目录表来获取那部分信息吗?

【问题讨论】:

  • 并非每个数据库都通过自动生成序列来支持它们来实现自动增量列。 (IIRC,MySQL 和 SQL Server 都没有。)DdlUtils 可能更喜欢可移植性而不是灵活性,只是没有为那些这样做的人提供特殊的 API。

标签: postgresql ddlutils


【解决方案1】:

回答我自己的问题... 是的,就像 millimoose 建议的那样,使用 DdlUtils 无法做到这一点,您必须查询 information_schema.columns 表:

public String getPostgreSQLSequenceForColumn(String database, String table, String column) {
    try {
        Statement stmt = connection.createStatement();
        String sql="select column_default from information_schema.columns where "+
                   "table_catalog='"+database+"' and "                           +
                   "table_schema='public' and "                                  +
                   "table_name='"+table+"' and "                                 +
                   "column_name='"+column+"'";
        ResultSet rs = stmt.executeQuery(sql);
        rs.next();
        String sequenceName = rs.getString(1);
        panicIf(rs.next());
        return sequenceName;
    } catch (Exception e) {
        throw new ExceptionAdapter(e);
    }
}

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 2010-12-07
    • 2014-12-12
    • 2012-06-21
    • 2021-03-19
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    相关资源
    最近更新 更多