Reputation: 16561
Using hibernate for data access.
I have a column in database:
varchar(40), default value is set to 0, NOT NULL
I have a case, that user sends null value, and getting error:
Error: org.hibernate.exception.ConstraintViolationException: Cannot insert the value
NULL into column 'foo', table 'MyTable'; column does not allow nulls. INSERT fails.
And the column in hibernate is defined like this:
@Column(name = "foo")
private String foo;
Where could the problem be? Must I define the default in hibernate annotations or smthing? How? Or any other suggetsions?
Upvotes: 0
Views: 7055
Reputation: 11735
What did you expect would happen when trying to insert NULL
into a NOT NULL
column? Either you want to enforce a NOT NULL
constraint, and then you need to reject the user input, or you want to accept NULL
values and need to specify that the column is nullable using, of course, @Column(nullable = true)
.
Since you actually want a default value in the column when the user doesn't provide that field, and your code explicitely sets the field value even when it's null (or empty, which is the same for Oracle, for example), I suggest having a smarter setter on the field:
private String foo = "0";
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
if (foo != null && !foo.isEmpty()) { // Or StringUtils.isNotBlank(foo)
this.foo = foo;
}
}
Upvotes: 2
Reputation: 16158
Default value for foo
would be null as it is class field.
As it's default value you are going to save is 0.
Make foo
primitive type if possible i.e. int
. If foo
has to be String, then you may remove not-null constraint, because even if you don't assign value to foo
, there is default value 0.
Suggestion : Consider Automatic POJO classes generation using Hibernate-Tools. This will auto generate your POJO classes from existing database.
Upvotes: 0
Reputation: 30875
If you table do not allow null value you sould respect that and adopt your model.
As you are using @Column annotation you should first set the property nullable to false, to support the default value you should also use the column definition.
@Column(name = "foo", nullable = false, columnDefinition = “varchar(40) default 0″)
Upvotes: 0