Hibernate. How can I add an entry to a table that has 2 foreign keys from 2 different tables in Hibernate?

116
August 29, 2021, at 6:40 PM

I have three tables

  1. User
  2. Order
  3. Invoice

User has @OnetoMany mapping to Invoice table and Order has @OnetoMany mapping to Invoice table. That means, Invoice table has 2 foreign keys, one coming from User table and the another from Order table (say 'user_fk' and 'order_fk').

In hibernate, I cannot add an invoice through user. It gives out an error saying that

"The column 'order_fk' cannot be null"

The same happens when I try with Order table. I understood why this error is showing up. I want to know the solution for this. How can I add an entry to a table that has 2 foreign keys from 2 different tables in Hibernate ?

Answer 1

You should first create both User and Order. Then instead of creating Invoice through User try to just create Invoice object with given User and Order. Saving such object should proceed without any issues. If that doesn't help try to add schema of your database and code that you are using for creating and saving those objects to DB.

Rent Charter Buses Company
READ ALSO
How can I add to shortcodes?

How can I add to shortcodes?

I have plugin A that needs to verify two pieces of shortcodes before an action takes place within another plugin

80
Change type / len of a user defined column in My SQL Workbench

Change type / len of a user defined column in My SQL Workbench

I am using a MySQL query in Workbench that uses group_concat() to group multiple string values

111