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

使用Java Spring和CrudRepository能否不填充所有列插入表新行?

解决方案

你遇到的限制本质是Kotlin默认声明的属性为不可空类型,不允许接收null值,和CrudRepository本身无关,按以下步骤调整即可实现直接存储null到PostgreSQL:

步骤1:修改实体类为可空属性

把需要支持空值的author_committed、date_committed两个字段改为Kotlin可空类型(后缀加?),同时添加@Column(nullable = true)声明对应数据库列允许空值:

@Entity
@DynamicUpdate
@Table(name = "subsets", schema = "public")
class Subsets(
    @Id
    val id: String,
    val author_created: String,
    val date_created: LocalDate,
    // 改为可空类型,设置列允许为空
    @Column(nullable = true)
    var author_committed: String?,
    @Column(nullable = true)
    var date_committed: LocalDate?,
) {
   // 无参构造对应调整默认值为null
   private constructor() : this("", "", LocalDate.now(), null, null)
} 

注:这里将两个可空字段改为var而非val,方便后续补全数据时直接修改属性更新。

步骤2:调整接口插入逻辑

插入时直接给两个字段传null即可,无需使用空字符串、特殊日期这类占位值:

@PostMapping("/createsubset")
fun createSubset(
    @RequestParam id: String,
    @RequestParam author_created: String,
){
    subsetsRepository.save(
        Subsets(
            id = id,
            author_created = author_created,
            date_created = LocalDate.now(),
            author_committed = null,
            date_committed = null
        )
    )
}

注意事项

  • 请确认你的PostgreSQL对应表的author_committed、date_committed列没有加NOT NULL约束,否则写入null时会触发数据库报错
  • 后续需要补全这两个字段时,正常给属性赋值非空值后调用save方法更新即可,@DynamicUpdate注解会保证只更新修改的字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:18:01