是否可以指示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对列creation_date有以下定义:

creation_date timestamp without time zone NOT NULL DEFAULT now()

作为conslusion,当我没有将特定值设置为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-值?

顺便说一句,我在PostgreSQL。这和PostgreSQL方言有关吗?

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

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

IIRC,如果插入为null,Hibernate应该在执行插入时抛出异常。通过这种方式,你必须确保它总是设置好的。

另一个选项是为creationDate:设置默认值

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

最新更新