user3663882
user3663882

Reputation: 7357

Is it possible to instruct hibernate not to set null values while performing insert?

I have the entity:

@Entity
@Table(name = "message")
public class Message {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "email")
    private String email;

    @Column(name = "subject")
    private String subject;

    @Column(name = "content")
    private String content;

    @Column(name = "html")
    private String html;

    @Column(name = "status")
    private Integer status;

    @Column(name = "creation_date")
    private Date creationDate;

    @Column(name = "send_date")
    private Date sendDate;

    //GET, SET
}

The table message has the following definition for the column creation_date:

creation_date timestamp without time zone NOT NULL DEFAULT now()\

As a conslusion, when I don't set a specific value to creation_date, hibernate will generate a query which looks like as follows:

insert into partner.message (content, creation_date, email, html, send_date, status, subject) 
values ('text', null, 'text', 'text', null, '1', 'text')

Is it possible to avoid generating those null-values?

BTW, I'm on PostgreSQL. Does it have something to do with PostgreSQL-dialect?

Upvotes: 4

Views: 3236

Answers (1)

Stefan
Stefan

Reputation: 1433

You should set your column creationDate as non nullable:

@Column(name = "creation_date", nullable = false)
private Date creationDate;

IIRC, Hibernate should throw an exception when doing an insert if it is null. This way you have to make sure it is always set.

Another option is to have a default value for creationDate:

@Column(name = "creation_date", nullable = false)
private Date creationDate = new Date(); //Or set it in the constructor

Upvotes: 5

Related Questions