Win a flower (🌹) or copy of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java (📚) this week in the Agile and Other Processes forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
master stewards:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
garden masters:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
gardeners:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

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

 
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
 
Yes, of course, and I accept that blame. In fact, i covet that blame. As does this tiny ad:
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!