开发者

Hibernate: Insert a new row by changing a portion of a composite-id primary key?

I am trying to insert new rows into the database but failing to get Hibernate to recognize that my objects must be inserted. I have a Sponsor table, a Course table, and a SponsorCourse table which is an intersection between the two. The primary key of a SponsorCourse is a composite-id of class SponsorCoursePK which holds two integers: the primary key of a Sponsor and the primary key of a Course. SponsorCoursePK implements equals() & hashcode().

My goal 开发者_StackOverflow中文版is a deep copy of the Course table, including all of its SponsorCourse rows.

  • I first ask Hibernate for a list of the SponsorCourses associated with the existing Course row.
  • Next I make a new Course object and commit that to the database. (For legacy reasons, Course objects are not managed by Hibernate).
  • Next I iterate over the list of SponsorCourses which Hibernate gave me for the old course, and change the portion of the SponsorCourse's primary key which holds the courseid from the old courseid to the id of the newly created course.
  • Next I call saveOrUpdate to attempt to get Hibernate to create the new rows.

When I look at the SQL Hibernate sends, no 'insert' statements exist: Hibernate fails to recognize that my new objects are 'dirty' and need to be inserted, even though I have changed a portion of the primary key. If I change any other value of the SponsorCourse, Hibernate will recognize the object as dirty and insert a new row.

My alternate approach is to create entirely new SponsorCourse objects and persist those. I am confused because for other child tables where the primary key is not a composite primary key, it appears to work to fetch a row, change the primary key, and then allow Hibernate to insert a new row based on the dirty object with a new primary key.

The Hibernate docs, in particular Chapter 8.4 (composite id's) & Chapter 10 (discussing modification of objects) of the Hibernate 3.0 reference have not been enough to help me understand.

Am I expecting something wrong by thinking I can change the primary key of an object fetched by Hibernate and thinking it will insert a new row? Should I always create my own, new, objects in that type of situation? Or, is it a problem unique with attempting to force an insert by changing part of a primary key which is a composite-id?

Thank you. Probably obviously, I am new to the framework.


I would try the following:

  1. Session.evict() the persistent object
  2. Changing the id
  3. Persist it using Session.replicate()

http://docs.jboss.org/hibernate/core/3.5/api/org/hibernate/Session.html

Good luck

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜