Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doesn't work setting default value of property in Hibernate

I have a boolean property in my entity. Here's my annotations for it:

@Column(name = "IS_ACTIVE", nullable = false, columnDefinition="BIT DEFAULT 1", length = 1)
public Boolean getActive() {
    return isActive;
}

But columnDefinition="BIT DEFAULT 1" doen't work perfectly. Here's SQL code I get as result for generated table:

IS_ACTIVE BIT(1) NOT NULL,

What am I doing wrong?

And so when I try to save an instance of this class to the database I get the exception:

`com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'IS_ACTIVE' cannot be null`

If I remove nullable = false property:

@Column(name = "IS_ACTIVE", columnDefinition="BIT DEFAULT 1", length = 1)
public Boolean getActive() {
    return isActive;
}

so I can save a created object in this case. But it's still the default value is not set and I get NULL in the value of this field in database.

Any ideas please? I use MySQL Server 5.1 if it's important. I would be very grateful for any help. Thanks in advance!

like image 262
Philiph Bruno Avatar asked Nov 27 '12 22:11

Philiph Bruno


People also ask

What is the default value in hibernate?

Default column values in JPA. JPA allows to generate Schema definitions when you set hibernate. hbm2ddl. auto value to create or create-drop or update .

What is the default annotation for a property in hibernate?

The default annotation for a property in the Java framework is a @ld annotation, where Hibernate assumes that the annotation is on the object's access properties and detects that it is on the field.


2 Answers

Try using BOOLEAN data type, define your @Column annotation like that:

@Column(name = "IS_ACTIVE", columnDefinition = "boolean default true", nullable = false)
private Boolean active = true;
like image 97
Aleksandr M Avatar answered Oct 28 '22 10:10

Aleksandr M


reference to the correct answer in this link How to set default value in Hibernate

If you want a real database default value, use columnDefinition - @Column(name = “myColumn”, nullable = false, columnDefinition = “int default 100"). Notice that the string in columnDefinition is database dependent. Also if you choose this option, you have to use dynamic-insert, so Hibernate doesn't include columns with null values on insert. Otherwise talking about default is irrelevant.

The key of the solution is dynamic-insert annotation. You can add it to your entity class as this example: @org.hibernate.annotations.Entity(dynamicInsert = true)

like image 42
Peter T. Avatar answered Oct 28 '22 10:10

Peter T.