Doesn't work setting default value of property in Hibernate

Philiph Bruno picture Philiph Bruno · Nov 27, 2012 · Viewed 46.2k times · Source

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!

Answer

Aleksandr M picture Aleksandr M · Nov 27, 2012

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;