apache / apache/grails-core

BSON serialization problem for domain classes with a discriminator

Open
#14,385 0 comments 0 reactions 0 assignees View on GitHub
relates-to: grails-data-mongodb
Dominant language
Groovy
Stars
2.9k
Forks
975
Avg merge
1d 22h
Merged PRs (30d)
92

Description

Upgrading an application from Grails 3.2.8 to Grails 4.0.5 (GORM 7.0.x) exposed a problem with domain classes mapped as a hierarchy: after a successful .save() on a domain instance, retrieving it back via .get() would result in a partially filled instance. A number of properties would not have their values loaded, and be left at null values. No exception or errors would be reported by GORM.

The base domain class in the application has "_class" persistent property defined for receiving discriminator values.

An inspection of the runtime GORM behavior shows that BsonPersistentEntityCodec writes out the discriminator "_class" property, and then does it again as a part of the persistent property set - see its encode method. The resulting class representation in persistent storage has two "_class" properties. This is possible because Mongo BSON allows storing duplicate properties.

On deserializing the domain class the discriminator-named property gets encountered twice. Processing the second occurence discards the partially resolved domain instance and creates a new instance to fill with property values - see decode method.

Removing the _class property definition from the domain class has the effect of it getting added/persisted by the codec as a dynamic attribute. The resulting BSON representation of the class still has two _class properties.

A workaround is to keep the _class property in the domain class, but define it as transient. This results in only the discriminator property getting serialized into BSON, with deserialization not getting re-started midway, and the domain instance getting loaded fully.

Contributor guide

Open the contributing guide

Research direction

Start by reading BsonPersistentEntityCodec.encode and decode, focusing on how the _class discriminator and persistent properties are processed. Reproduce the save-then-get case with a domain hierarchy and inspect the stored BSON. Done means the discriminator is not duplicated and the retrieved domain instance retains its property values.

Written by the indexing model from the issue text.

Assessment

Tech stack
mongodb
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.