0

我有一个Student需要保存在数据库中的对象。id :studentId的定义类似于 HBM :-

        <id name="studentId" type="long">
            <column name="ST_ID" />
            <generator class="native" />
        </id>

现在,为了生成 ID,我编写了我通常实现的代码,与 hibernate Source 中的代码相同,如下所示:-

// fetching the entity persister for the entity
EntityPersister persister = 
    ((SessionImpl)session.).getEntityPersister(entity.getClass().getName(), entity);

// get the model 
PersistentClass model = configuration.getClassMapping(persister.getEntityName());

// cache concurrency
CacheConcurrencyStrategy strategy = persister.getCache();
Class persiterClass = model.getEntityPersisterClass();

SessionFactoryImpl  sessionFactoryImpl = 
            (SessionFactoryImpl) session.getSessionFactory();

if(persiterClass == null) {     
    persister = new SingleTableEntityPersister(model, strategy, sessionFactoryImpl)
}

this.id = persister.getIdentifierGenerator().generate((SessionImpl)session, entity);

persister.setIdentifier(entity, id, EntityMode.POJO);

现在,当我到达代码行时persister.setIdentifier(entity, id, EntityMode.POJO);,出现以下异常:-

IllegalArgumentException in class:
com.school.class.Student, setter method of property: studentId
org.hibernate.property.BasicPropertyAccessor$BasicSetter set
SEVERE: expected type: long, actual value: org.hibernate.id.IdentifierGeneratorFactory$2
org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of com.school.class.Student.studentId
    at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:104)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.setIdentifier(AbstractEntityTuplizer.java:211)
    at org.hibernate.persister.entity.AbstractEntityPersister.setIdentifier(AbstractEntityPersister.java:3601)
    at com.school.class.Student.<init>(Student.java:140)

请帮助,因为我无法理解错误,因为我从休眠中选择了相同的代码。如果它在那里正常工作,那么这段代码也应该在这里工作。

谢谢

4

3 回答 3

1

一些生成器无法在实际插入之前生成标识符,因此它们从generate()方法中返回一个特殊的标记对象。该对象表示 Hibernate 应该以不同的方式获取标识符,使用PostInsertIdentifierGenerator.getInsertGeneratedIdentifierDelegate()方法。

于 2011-06-22T09:27:13.507 回答
0

该错误是由于Student该类没有该方法引起的setStudentId{Long id)

于 2011-06-22T08:01:41.697 回答
0

在 HBM 文件中,我提到生成器为<generator class="native" />,它无法正常工作,然后我尝试使用<generator class="increment"/>,我不知道确切原因,但它可以正常工作。

我觉得正确的原因可能是标识符生成器是POST_INSERT_INDICATOR,我觉得这意味着将在对象插入数据库后生成 id,而我试图在插入之前生成相同的,这就是它失败的原因.

我什至也尝试过使用其他 id 生成器,Refer This,我尝试过uuid, assigned, increment, sequence, and hilo,它们工作正常,但是native& identity,同样的问题失败了。

邀请对此答案进行任何更新,因为即使我想知道这件事的确切原因,也想知道确切的原因。

于 2011-06-24T04:45:33.013 回答