是否有可能在执行插入时指示hibernate不设置空值?

时间:2015-04-08 11:18:38

标签: java hibernate

我有实体:

@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
}

message对create_date列有以下定义:

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

作为一个结论,当我没有为creation_date设置特定值时,hibernate将生成一个如下所示的查询:

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

是否可以避免生成null - 值?

BTW,我在PostgreSQL。它与PostgreSQL - 方言有什么关系吗?

1 个答案:

答案 0 :(得分:4)

您应该将列creationDate设置为不可为空:

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

IIRC,Hibernate在执行插入时应该抛出异常,如果它为null。这样你必须确保它始终设置。

另一种选择是为creationDate设置默认值:

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