4

Is it possible in Spring Boot using Spring Data JPA to insert an entity with a foreign key without resorting to getting first the foreign entity object?

From what I can do is, I have to first query the Department and use the resulting object as the foreign key object to my Employee entity.

So what's happening is

  1. findDeptByDept - use that object and store it to currentDept
  2. use currentDept to Employee object dept setter method (emp.setDept)
  3. save

I know before hand what dept id is. Actually, I have a list of emps with their corresponding dept id. Is it really necessary to query first the dept object and set that object to emp.setDept(dept)?

Is there away not to do this in hibernate under spring boot and spring data?

3
  • Possible duplicate of Hibernate persist entity without fetching association object. just by id Commented Sep 24, 2016 at 20:06
  • Hi Dragan, Thanks! Question though, why is this hibernate's way doing things? There must be something I am missing why Hibernate if forcing programmers to do this. Commented Sep 25, 2016 at 4:16
  • Hibernate is not forcing you to do this, basically you told it to do it by specifying cascade options. If a cascade option is applied to an object so that the object becomes managed (tracked in the persistence context), Hibernate has to know what the current state of the object is in the database, so that it can properly save changes (dirty check), etc. Commented Oct 4, 2016 at 21:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.