Is it possible to have the same classes be @Entity and @Embedded? (2.0.2)
See original GitHub issueI am storing certain objects as both separate entities in a collection and embedded within other entities in different collections (for caching, basically). Prior to 2.0 I have been using the same class for both without any issues, however in 2.0 it is causing various issues.
Now that @Embedded
has to be used on types, the constraints don’t let me use both @Embedded
and @Entity
on the same class, and they also neither allow an @Embedded
class with an @Id
property, nor they allow an @Entity
class without one.
The structure I have is kind of like this (actually there is a base class for Job
to make this possible but just to have a shorter example):
@Entity("job")
@Indexes(Index(fields = [Field("shifts.startTime", type = IndexType.ASC)]))
class Job(
@Id var id: ObjectId,
var shifts: List<Shift>,
)
class Shift(
@Id var id: ObjectId,
var startTime: Date,
)
// and also
@Entity("shiftAndJob")
class ShiftAndJob(
var shift: Shift,
var job: Job,
)
-
Mapping fails with a
ValidationException
on theshifts.startTime
index, it’s not being found. -
If I try to retrieve a
Job
entity, the operation fails withorg.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class Shift
. -
Validations fail when trying to query
ShiftAndJob
for e.g.job.shifts
orshift.startTime
So basically I want to use the Job
class here as both an embedded object and its own separate entity and I can’t figure out what’s the way to do so in 2.0 (in 1.* it all just worked regardless of @Embedded
), are there any “best practices” on how to achieve this without cloning the classes altogether or using too much inheritance?
Driver Version: 4.0.5
Morphia Version: 2.0.2
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (3 by maintainers)
You can just use
@Entity
on the type and then also embed. The annotations are there to mark which classes to map and which set of validations to apply, to perhaps oversimplify things a bit. But an entity can also be embedded at that point because it’s already mapped. I believe there are some unit tests that do just that.Yes, it’s working fine, thank you!