0

TL;DR : Can you tell JPA, please do not insert this value into the DB, if it is null? Let the database DEFAULT it out.

Long version:

Let's say that I have the following database column, in a table:

IS_JOE_COOL_FLAG VARCHAR2(1 BYTE) DEFAULT 'N' NOT NULL 

Say that I have a REST service, in which IS_JOE_COOL_FLAG is an optional parameter. i.e The user might send it, or they might not.

What I want to do is tell my java code, using JPA, don't insert anything into the database column IS_JOE_COOL_FLAG if the same REST parameter is null. Let the database do it's thing.

Such a question exists on Stack already, located here.

The author of the selected answer makes this statement:

Choose the pragmatic approach here and initialise all values in java. Never heard of a way to tell JPA/Hibernate to leave out null values in an insert/update.

Instead, he argues that you ought to just tell JPA what to send.

The author of the second answer states that this problem could be solvable with the following code:

@Column(insertable = false)

Looking at some documentation, and the comments made underneath the answer, this flag does NOT solve that problem. It completely prevents the column from being inserted, period. I have tested this out on my local machine, and the documentation and comments do check out.

There are other suggestions, stating that the DEFAULT code can just be put in the column definition of the JPA entity. However, in my opinion, that just defeats the purpose of creating the default comment on the SQL side.

So now that it's been roughly 8 more years since that question has been posted, ( I apologize if I've missed a newer edition ), I am still a bit confused if there is an actual solution to this or not.

pirho
  • 11,565
  • 12
  • 43
  • 70
angryip
  • 2,140
  • 5
  • 33
  • 67

2 Answers2

0

One approach could be to put validation on the db side to fail the transaction if the field is missing: aka require it be present. Is there a specific reason this type of validation needs to be through JPA and not through the service layer? a simple null check could prevent a database call entirely.

0

You can define a @Converter and override its convertToDataBaseColumn() to insert null always ... thus the default DB value will be used

osama yaccoub
  • 1,884
  • 2
  • 17
  • 47