Hibernate - 编程配置

时间:2008-11-30 10:17:06

标签: hibernate configuration

我正在尝试不是通过XML / Annotation配置Hibernate类,而是使用他们的编程API:

Mappings mappings = configuration.createMappings();
    mappings.addClass(...);

添加列的示例:

public void addColumn(String colName, String accessorName, NullableType type)
      {
        if(this._table == null)
          {
            return;
          }

        Column column = new Column(colName);
//        this._table.addColumn(column);

        Property prop = new Property();
        prop.setName(accessorName);

        SimpleValue simpleValue = new SimpleValue();
        simpleValue.setTypeName(type.getName());
        simpleValue.addColumn(column);
        simpleValue.setTable(_table);
        prop.setValue(simpleValue);

        this._rootClass.addProperty(prop);
      }

这是有效的,直到我第一次需要添加一个名称已经存在的列。它不是我在同一个表中添加相同的列,这是两个不同的表,但是,我收到了

 ERROR:  java.lang.NullPointerException
    at
 org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:711)

我检查了源代码(我使用的是Hibernate 3.3.1 GA),在PersistentClass中有一行,第711行:

protected void checkColumnDuplication() {
    HashSet cols = new HashSet(); <=========After this line 'cols' already contain data!
    if (getIdentifierMapper() == null ) {
        //an identifier mapper => getKey will be included in the getNonDuplicatedPropertyIterator()
        //and checked later, so it needs to be excluded
        checkColumnDuplication( cols, getKey().getColumnIterator() );
    }
    checkColumnDuplication( cols, getDiscriminatorColumnIterator() );
    checkPropertyColumnDuplication( cols, getNonDuplicatedPropertyIterator() );
    Iterator iter = getJoinIterator();
    while ( iter.hasNext() ) {
        cols.clear();
        Join join = (Join) iter.next();
        checkColumnDuplication( cols, join.getKey().getColumnIterator() );
        checkPropertyColumnDuplication( cols, join.getPropertyIterator() );
    }
}

是否有人试图像这样配置它,有同样的问题?...

提前致谢

1 个答案:

答案 0 :(得分:1)

你的空指针是因为你还没有为你的RootClass对象提供一个实体名称 - 你只需要在根类上调用setEntityName,你就会超越初始异常。

您还需要在根类上定义标识符值 - 只需使用您要设置标识符的值调用setIdentifier。 (不要再使用此方法调用addProperty,否则会抱怨列重复)。