• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic