Snox
Snox

Reputation: 588

Hibernate default varchar value - Postgres

I have a Postgres database that i have mapped with Hibernate, and everything was working fine until i had the need of adding a new attribute. I've added an attribute "ROLE" which needs to be not null and have the value "USER" by default. In Postgres i have ROLE VARCHAR(60) NOT NULL DEFAULT 'USER' which i believe is correct, and i also have

@Column(name = "role", length = 60, nullable = false, columnDefinition = "varchar(60) default 'USER'")
public String getRole() {
    return this.role;
}

The thing is, when i try to create a new entry in my DB it fails - not-null property references a null or transient value

I've tried everything but no luck... From what i read, what i have should have worked. Can anyone help please?

Thank you.

Upvotes: 2

Views: 2287

Answers (1)

flob
flob

Reputation: 3908

For most cases it should work out if you just set the role to your default value.

Otherwise it will be set to null as this.role will be null during save and so that value will get persisted.

  • Default value as initial value of the field:

    private String role = "USER";
    
  • Use a org.hibernate.usertype.UserType and override null during save:

    @Override
    public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException
    {
        if (value == null)
            st.setString(index, "ROLE");
        else
            st.setString(index, s);
    }
    
  • Use a @PrePersist and @PreUpdate method and set the default value with:

    if (this.role == null) { this.role = "USER"; }
    

If you get objects with that value set to null from outside like deserialized JSON or XML you might need to use @PrePersist or a UserType, otherwise just setting the default value should be fine.

  • You could use Hibernates dynamic update statement dynamic-update=true and dynamic-insert=true. It generates insert statements for each insert that dosn't insert null values and thus uses the DB default value.

Upvotes: 4

Related Questions