简体   繁体   中英

Adding null value to NOT NULL table, org.hibernate.exception.ConstraintViolationException

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?

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;
    }
}

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 ie 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.

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″)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM