开发者

Many to one (item - type relation): identifer was change from x to y

I have 2 class Item & Type. An Item belongs to one type.

It works ok. But when I try to change TYPE of an already saved item, it brings out the error:

identifier of an instance of com.myapp.model.Type was altered from 1 to 2.

It seems that Hibernate is thinking that I try to edit the id of Type. Actually, I want to change the Type of an item, not edit the type it is in. For a quick example, I have an Item name "Ball" belongs to "sport" type, but now I want to change it to "Tool" type. And Hibernate think that I want to change the name (and Id) of "Sport" type into "Tool"!

开发者_如何学Python

Pseudo code:

Item item = getItemFromDatabase(itemId);
item.setType(newType);
saveItem(item);

My mapping files:

<hibernate-mapping>
    <class name="com.myapp.model.Item" table="ITEM">
        <cache usage="read-write"/>
        <id name="id" column="ID">
            <generator class="sequence">
                <param name="sequence">item_seq</param>
            </generator>
        </id>

        <property name="name" column="NAME"/>
        <many-to-one name="type" 
             class="com.myapp.model.Type"
             column="type_id" 
             foreign-key="ITEM_TYPE_FK"
              />

        <property name="description" column="DESCRIPTION"/>
    </class>
</hibernate-mapping>

And

<hibernate-mapping>
    <class name="com.myapp.model.Type" table="TYPE">
        <cache usage="read-write"/>
        <id name="id" column="ID">
            <generator class="sequence">
                <param name="sequence">type_seq</param>
            </generator>
        </id>

        <property name="name" column="NAME"/>
    </class>
</hibernate-mapping>

Does I misunderstand anything?

UPDATE:

I have an Hibernate utility function like this:

    @Override
    @SuppressWarnings("unchecked")
    public <T> T getById(Class<T> entityClass, Serializable id) {
        try {
            Object result = this.sessionFactory.getCurrentSession().get(entityClass, id);
            if (result != null) {
                return (T)result;
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new DataAccessException(e);
        }
    }

Then in my code, I just call:

Type updatedType = repository.getById(Type.class, item.getType().getId());


The way that I think is correct is

Item item = getItemFromDatabase(itemId);
item.setType(getItemTypeFromDatabase(newTypeId));
saveItem(item);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜