我有一個用戶對象與字符串類型具有一對多的關係。我相信他們是簡單的映射。類型表保存關聯的user_id和變量類型名稱,主鍵「id」基本上是一個計數器。休眠保存奇怪的行爲
<class name="Users" table="users">
<id column="id" name="id" />
...
<set name="types" table="types" cascade="save-update">
<key column="id" />
<one-to-many class="Types" />
</set>
</class>
<class name="Types" table="types">
<id column="id" name="id" />
<property column="user_id" name="user_id" type="integer" />
<property column="type" name="type" type="string" />
</class>
這是我用於添加到數據庫中的Java:當我檢查SQL
61468 [http-8080-3] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000
61468 [http-8080-3] ERROR org.hibernate.util.JDBCExceptionReporter - Duplicate entry '6' for key 'PRIMARY'
61468 [http-8080-3] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
,它:
User u = new User();
u.setId(user_id);
...
Collection<Types> t = new HashSet<Types>();
t.add(new Type(auto_incremented_id, user_id, type_name));
u.setTypes(t);
getHibernateTemplate().saveOrUpdate(u);
當我運行它,它給這個錯誤顯示:
Hibernate: insert into users (name, id) values (?, ?)
Hibernate: insert into types (user_id, type, id) values (?, ?, ?)
Hibernate: update types set id=? where id=?
- 爲什麼Hibernate嘗試更新類型的ID?
錯誤說:關鍵'PRIMARY'重複條目'6',但真的沒有?我確保每次都增加id。用戶和類型正確添加到數據庫中。
我記錄了進去的信息,添加的類型有一個id爲7,用戶id是6.可能是Hibernate的user_id是6,試圖更新類型並設置id = 6,其中id = 7?因此重複的主鍵錯誤?
但是它爲什麼會這麼奇怪?有沒有辦法阻止它更新?
- 我應該手動設置ID嗎?如果不是,那麼我應該如何添加這些類型?當我添加只有一個類型字符串和沒有ID的類型對象時,它會給出其他錯誤。
謝謝你們。我們已經仔細研究了幾天...
套牢元素集合!謝謝! – April 2009-07-13 14:33:14