使用Hibernate SessionFactory获取列大小

时间:2013-01-30 22:01:52

标签: hibernate

我正在尝试检索表的元数据信息;我成功地检索了表中的列和列的类型。我也想检索每个列的大小。我对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)

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

你看错了地方。正如其名称所示,ClassMetadata包含有关类的元数据,而不是数据库表及其列。

要获取有关表格列的信息,请使用JDBC's DatabaseMetaData