Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate On Duplicate Entry

 
Neo Say Bin
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

Have a question to ask regarding my project. My project uses Hibernate with MySQL. Records are modified and saved/updated via Hibernate. The project does not make direct JDBC calls to MySQL. When I try to save or update an object, Hibernate throws an exception about the duplicate entry. An example of my code to save the object is as follows:

// Code here to open the session and get the object to save or update

// try to save or update the object
session.saveOrUpdate(obj);

// flush the object
session.flush();

Example of the Hibernate mapping of the object:

<hibernate-mapping>
<class name="ChatSession" table="chat_session">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<set name="participant" cascade="all">
<key column="parent_id"/>
<one-to-many class="Participant"/>
</set>
<property name="name" type="string"/>
</class>

<class name="Participant" table="participant">
<id name="id" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>

After doing some research, I think my problem is pertaining to the following entry:

http://www.jroller.com/mmatthews/entry/getting_hibernate_and_mysql_s

However, I'm not sure what the solution is. What do I modify in my application code or hibernate mapping file or settings to resolve this problem?

Thks a lot for the help. Regards.
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I bet you're loading a POJO through Hibernate, putting it in an HttpSession somewhere, and then retrieving it. When you retrieve it, Java gives the POJO a new memory address, and when you put it back into Hibernate, the Hibernate Session thinks it's a new object, which clashes with the one already in the Hibernate cache. Possible?

The question is why are you adding a POJO to the Hibernate session when it already exists there?

You might find this tutorial helpful. It explains how POJO's get out of sync with the Session, and how detached, persistent and transient objects are treated by the Hibernate Session:

How Hibernate Works - Understanding the Hibernate3 Session

-Cameron McKenzie
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic