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.

1
  • I think that a INSERT without the columns that is null will fall to the default value of it, try to look a way to ignore it Commented Feb 16, 2018 at 19:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think the default keyword should do exactly the same
while this is just an example, modifying the database layer at this point, is definitely not an option.
0

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

Comments

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.