Win a copy of Classic Computer Science Problems in Swift this week in the iOS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Hibernate how to add a new row to a table with a foreign key  RSS feed

Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am using Java8 with Hibernate and MySQL.

I have the following tables with a join table:

(A `PERSON` can have many `JOBs`)

When I try save a new `JOB`, it has a foreign key join to and existing `PERSON`. It looks like Hibernate wants to also save a new `PERSON`, resulting in a duplicate entry.  I thought Hibernate would be smart enough, that if there is already a matching `PERSON`, it won't try save it again.

Resulting in the following error when trying to save a row in the `JOB` table:

>     MySQLIntegrityConstraintViolationException: Duplicate entry '338-1688' for key 'PRIMARY'



When I run in debug mode, I see the new `Job` row it is trying to `merge` has an `ID` of `26` and a `PERSON` with an `ID` of `338` as expected.


How do you create a new entry on one table (`JOB`), that has a foreign key join to an existing entry (`PERSON`)?

i.e. I want to just maintain a `@ManyToOne` relationship.

Please can anyone assist.


If I try `persist` instead of `merge`, I get:


> detached entity passed to persist:
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!