Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hibernate

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?

like image 809
user3663882 Avatar asked Nov 01 '25 08:11

user3663882


1 Answers

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
like image 60
Stefan Avatar answered Nov 03 '25 21:11

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!