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

Scala中Neo4j OGM保存实体报错:主键字段为null

Fixing Neo4j OGM MappingException for Custom String ID in NodeEntity

Let's break down why you're hitting this error and how to fix it:

Root Cause

Your current setup has two conflicting issues:

  1. You’re using @GeneratedValue alongside manually setting the ID (via sutStateIdentifier.hash). Neo4j OGM interprets @GeneratedValue as a signal that it should handle ID creation, which clashes with your custom ID logic.
  2. The id field is defined as a val (immutable). Neo4j OGM requires mutable fields (Scala var) for entity identifiers, as it needs to perform reflection-based operations (like state sync during persistence) that require a setter.

Fixed Code

Update your SutStateEntity class like this:

@NodeEntity 
class SutStateEntity(
  @Id 
  @Index(unique = true) 
  var id: String
) { 
  def this(sutStateIdentifier: SutStateIdentifier) = this(sutStateIdentifier.hash) 
  def this() = this("") 
}

Explanation

  • Remove @GeneratedValue: Since you’re explicitly providing the ID via the hash of sutStateIdentifier, you don’t want OGM to generate an ID for you. This annotation was confusing OGM’s internal mapping logic, leading it to incorrectly flag the ID as null.
  • Switch from val to var: Scala vals generate private fields with only getters, no setters. Neo4j OGM relies on having a setter to manage the entity’s ID during the persistence lifecycle—even if you initialize it in the constructor. Using var ensures the necessary setter exists for OGM to work correctly.

Your working Long-type example worked because:

  • @GeneratedValue natively supports auto-generating Long IDs in Neo4j OGM
  • The var modifier provided the required setter for OGM to populate the generated ID

After making these changes, your code should save the entity with your custom hash-based ID without throwing the MappingException.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:33:47