gpt4 book ai didi

hibernate - Apache derby in-memory db schema dump with Hibernate 4+

转载 作者:行者123 更新时间:2023-12-02 09:46:53 24 4
gpt4 key购买 nike

我在单元测试中使用 Apache Derby 10.9.x 和 Hibernate Entitymanager 4.1.9.Final。 Derby db 模式是从 JPA 注释实体生成的。只有一个 persistence.xml 配置文件。我想在单元测试期间/之前/之后转储生成的 Derby db 模式。这样做的程序化方式是什么?

解决方案:

    // should not be required because Hibernate already started Derby:
//Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();

try (Connection conn = DriverManager.getConnection ("jdbc:derby:memory:unit-testing;")) {
String cat = null;
String schema = "ROOT";

DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTableTypes();
ResultSetUtils.dump(rs);
rs = md.getTables(cat, schema, null, new String[]{"TABLE"});
ResultSetUtils.dump(rs);
rs = md.getColumns(cat, schema, null, null);
ResultSetUtils.dump(rs);
}

公共(public)类 ResultSetUtils {
private static final Logger logger = Logger.getLogger(ResultSetUtils.class.getName());
private static final String COL_SEPARATOR = ";";

public static int getColForLabel(ResultSet rs, String labelname) throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();

for (int i = 1; i <= rsmd.getColumnCount(); i++) {
if (labelname.equals(rsmd.getColumnLabel(i))) {
return i;
}
}

throw new SQLException("Invalid label name " + labelname);
}

public static void dump(ResultSet rs) throws SQLException {

// the order of the rows in a cursor
// are implementation dependent unless you use the SQL ORDER statement
ResultSetMetaData meta = rs.getMetaData();
int colmax = meta.getColumnCount();
int i;
Object o;

StringBuilder sb = new StringBuilder(512);
for (i = 0; i < colmax; ++i) {
if(i>0) {
sb.append(COL_SEPARATOR);
}
String s = meta.getColumnName(i + 1);
sb.append((s == null) ? "NULL" : s);
s = meta.getColumnTypeName(i + 1);
sb.append((s == null) ? "(NULL)" : "("+s+")");
}
logger.info(sb.toString());


// the result set is a cursor into the data. You can only
// point to one row at a time
// assume we are pointing to BEFORE the first row
// rs.next() points to next row and returns true
// or false if there is no next row, which breaks the loop
for (; rs.next();) {
sb = new StringBuilder(512);
for (i = 0; i < colmax; ++i) {
if(i>0) {
sb.append(COL_SEPARATOR);
}
o = rs.getObject(i + 1); // Is SQL the first column is indexed
sb.append((o == null) ? "NULL" : o.toString());
}

logger.info(sb.toString());
}
}

}

最佳答案

访问模式的编程方式是使用 DatabaseMetaData 类:http://docs.oracle.com/javase/6/docs/api/java/sql/DatabaseMetaData.html

从 getTables() 方法开始,打印出返回的信息。

关于hibernate - Apache derby in-memory db schema dump with Hibernate 4+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15236750/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com