You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何结合Spring Boot PrePersist与Lombok @NonNull配置实体?

解决方案:Spring实体空安全与避免重复模型的处理

方案1:构造函数区分创建/查询场景

给实体类定义两个构造函数,分别对应创建对象(无需传入timestamp)和JPA查询实例化(需要timestamp)的场景,同时保留@NonNull约束保证查询后的字段非空,数据库层面添加nullable=false确保数据完整性:

@Entity
public class Customer {

    @Column(nullable = false)
    @NonNull 
    private Date timestamp;

    // 创建对象时使用的无参构造,无需传入timestamp
    public Customer() {}

    // JPA查询专用的私有构造,避免外部误用
    private Customer(Date timestamp) {
        this.timestamp = timestamp;
    }

    @PrePersist
    private void prePersistFunction(){
        if (this.timestamp == null) {
            this.timestamp = new Date();
        }
    }

    // 其他字段、getter/setter...
}

方案2:Builder模式+Lombok简化

借助Lombok的@Builder、@AllArgsConstructor和@NoArgsConstructor注解,实现创建对象时无需设置timestamp,同时保证查询后的空安全:

@Entity
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE) // 供JPA反射调用的私有全参构造
@NoArgsConstructor(access = AccessLevel.PUBLIC)    // 创建对象用的公共无参构造
public class Customer {

    @Column(nullable = false)
    @NonNull 
    private Date timestamp;

    @PrePersist
    private void prePersistFunction(){
        if (this.timestamp == null) {
            this.timestamp = new Date();
        }
    }

    // 其他字段...
}

创建对象时直接使用Customer.builder().build()即可,无需手动设置timestamp;JPA会通过私有全参构造实例化查询结果,保证timestamp非空。

方案3:编译期空安全警告抑制(不推荐)

如果只是想临时解决IDE的空安全警告,可以在创建对象的代码处添加@SuppressWarnings("null"),但这种方式不够直观,仅作为临时 workaround:

@SuppressWarnings("null")
Customer customer = new Customer();
// 其他初始化逻辑...

内容的提问来源于stack exchange,提问作者sss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 02:33:11