Cannot make @ManyToOne relationship nullable
Asked Answered
R

4

24

I have a many-to-one relationship that I want to be nullable:

@ManyToOne(optional = true)
@JoinColumn(name = "customer_id", nullable = true)
private Customer customer;

Unfortunately, JPA keeps setting the column in my database as NOT NULL. Can anyone explain this? Is there a way to make it work? Note that I use JBoss 7, JPA 2.0 with Hibernate as persistence provider and a PostgreSQL 9.1 database.

EDIT:

I found the cause of my problem. Apparently it is due to the way I defined the primary key in the referenced entity Customer:

@Entity
@Table
public class Customer { 
    @Id
    @GeneratedValue
    @Column(columnDefinition="serial")
    private int id;
}

It seems that using @Column(columnDefinition="serial") for the primary key automatically sets the foreign keys referencing it to NOT NULL in the database. Is that really the expected behavior when specifying the column type as serial? Is there a workaround for enabling nullable foreign keys in this case?

Thank you in advance.

Revere answered 19/3, 2013 at 22:40 Comment(0)
R
24

I found the solution to my problem. The way the primary key is defined in entity Customer is fine, the problem resides in the foreign key declaration. It should be declared like this:

@ManyToOne
@JoinColumn(columnDefinition="integer", name="customer_id")
private Customer customer;

Indeed, if the attribute columnDefinition="integer" is omitted the foreign key will by default be set as the source column: a not-null serial with its own sequence. That is of course not what we want as we just want the to reference the auto-incremented ID, not to create a new one.

Besides, it seems that the attribute name=customer_id is also required as I observed when performing some testing. Otherwise the foreign key column will still be set as the source column. This is a strange behavior in my opinion. Comments or additional information to clarify this are welcome!

Finally, the advantage of this solution is that the ID is generated by the database (not by JPA) and thus we do not have to worry about it when inserting data manually or through scripts which often happens in data migration or maintenance.

Revere answered 24/3, 2013 at 0:59 Comment(0)
C
6

I came across this problem but I was able to solve it this way:

@ManyToOne
@JoinColumn(nullable = true)
private Customer customer;

Maybe the problem emerged from declaring @ManyToOne(optional = true)

Corroboree answered 23/4, 2014 at 14:48 Comment(3)
nullable = false?? false? Why false, not true?Himyaritic
definitely it should be nullable = trueDeandra
Nullable is set to true by default, there is no need to define it.Hammerlock
P
0

That is very weird.

In JPA nullable parameter is true by default. I use this kind of configuration all the time and it works fine. If you try to save entity it should be successful.

Did you try to delete table that is created for this relationship? Maybe you have legacy table with that column?

Or maybe you should try to find solution on other chunks of code, because this is proper configuration.

Note: I have tried this configuration on PostgreSQL with JPA2 and Hibernate.

EDIT

In that case maybe you can try a little bit different definition of primary key.

For example you can use definition like this:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column()
private Long id;

and postgresql will generate

id bigint NOT NULL
-- with constraint
CONSTRAINT some_table_pkey PRIMARY KEY (id)

If this is good enough you can try this solution.

Pipistrelle answered 20/3, 2013 at 15:53 Comment(1)
That's indeed a solution I have considered. Unfortunately this does not enable ID generation from the database itself, and it's a functionality I need when inserting data manually (using hibernate's import.sql for instance). Luckily I guess I am about to find a solution. I am just doing some testing and if it's successful I'll post the solution. Thanks for your help.Revere
B
0

within transaction but before the save operation, explicitly set the foreign key column value as null. By this hibernate ,never perform select queries for this foreign key related table and don't throw the exception "save the transient instance before flushing". if you want to set "null value " conditionally, then perform 1. fetch & set the value using repo call get/ find 2. then check the fetched value for the condition and set it to null accordingly .pasted the code below which is tested and found working

//  Transaction Start 

   Optional<Customer> customerObject = customerRepository.findByCustomerId(customer.getCustomerId())

   if(customerObject.isPresent())yourEnclosingEntityObject.setCustomer(customerObject)}

   else {yourEnclosingEntityObject.setCustomer(null)}

   yourEnclosingEntityObjectRepository.save(yourEnclosingEntityObject)

//  Transaction End
Biplane answered 9/12, 2018 at 12:34 Comment(3)
there is always a workaround in life, would be nice to know how tooDownstairs
Nice to see the beginning of your edits in place, I had flagged the previous answer ["there is a workaround"] as not an answer. Thanks for helping but better if you do the job all at once next time to avoid flags and downvotes. Ciao!Downstairs
i'm a new contributor. ok . will doBiplane

© 2022 - 2024 — McMap. All rights reserved.