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:
- You’re using
@GeneratedValuealongside manually setting the ID (viasutStateIdentifier.hash). Neo4j OGM interprets@GeneratedValueas a signal that it should handle ID creation, which clashes with your custom ID logic. - The
idfield is defined as aval(immutable). Neo4j OGM requires mutable fields (Scalavar) 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 ofsutStateIdentifier, 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
valtovar: Scalavals 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. Usingvarensures the necessary setter exists for OGM to work correctly.
Your working Long-type example worked because:
@GeneratedValuenatively supports auto-generating Long IDs in Neo4j OGM- The
varmodifier 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é
相关产品推荐
相关产品推荐

