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

use*_*882 4 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
}
Run Code Online (Sandbox Code Playgroud)

该表message对创建日期列有以下定义:

creation_date timestamp without time zone NOT NULL DEFAULT now()\
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Ste*_*fan 5

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

@Column(name = "creation_date", nullable = false)
private Date creationDate;
Run Code Online (Sandbox Code Playgroud)

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

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

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