0

我正在尝试检索表的元数据信息;我成功检索了表中的列和列类型。我也想检索每个列的大小。我对 Hibernate 还很陌生,并且一直坚持这一点。这就是我检索列名和类型的方式:

String[] columns = HibernateUtil.getSessionFactory()
            .getClassMetadata(Java.class).getPropertyNames();
Type[] columnsType = HibernateUtil.getSessionFactory()
            .getClassMetadata(Java.class).getPropertyTypes();

实体类:

@Entity
    @Table(name="Box")
    public class Box implements Serializable {
        private int dimHeight;
        private int dimLen;
        private int dimWidth;
        private double weight;

        public Box() {
        }

        public int getDimHeight() {
            return this.dimHeight;
        }

        public void setDimHeight(int dimHeight) {
            this.dimHeight = dimHeight;
        }

        public int getDimLen() {
            return this.dimLen;
        }

        public void setDimLen(int dimLen) {
            this.dimLen = dimLen;
        }

        public int getDimWidth() {
            return this.dimWidth;
        }

        public void setDimWidth(int dimWidth) {
            this.dimWidth = dimWidth;
        }

        public double getWeight() {
            return this.weight;
        }

        public void setWeight(double weight) {
            this.weight = weight;
        }
    }

代码和异常是:

Field foo = Box.class.getField("dimWidth");
foo.setAccessible(true);

java.lang.NoSuchFieldException: dimWidth
    at java.lang.Class.getField(Class.java:1520)
4

2 回答 2

1

HibernateUtil没有暴露这一点。但是,您可以简单地使用 Java 反射:

Field foo = Java.class.getField("foo");
Column column = foo.getAnnotation(Column.class);
column.length();

更新

Grrrhh,犯了一个愚蠢的错误……getField()仅供公众使用。您需要getDeclaredField()像这样用于私有字段:

Field dimWidthField = Box.class.getDeclaredField("dimWidth");
Column columnAnnotation = dimWidthField.getAnnotation(Column.class);
System.out.println(columnAnnotation.length()); // 5
System.out.println(columnAnnotation.precision()); // 0

private class Box implements Serializable {
  @Column(length = 5, precision = 0)
  private int dimWidth;
于 2013-02-01T23:31:20.787 回答
0

You're looking at the wrong place. As its name indicates, ClassMetadata contains metadata about a class, and not about a database table and its columns.

To get information about the columns of a table, use JDBC's DatabaseMetaData.

于 2013-02-01T23:25:44.427 回答