Win a 3 month subscription to Marco Behler Videos this week in the Spring 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

 
RichardH Marais
Greenhorn
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'

**SQL**







**Job.java**




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.




**Question**

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.

**UPDATE**

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

   

> detached entity passed to persist: com.jobs.spring.domain.Person
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!