import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.bson.codecs.pojo.annotations.BsonId; import org.bson.codecs.pojo.annotations.BsonProperty; public class User { @BsonId @BsonProperty("_id") UUID id; private List<UserSession> sessions = new ArrayList<>(); } import java.time.Instant;
public class UserSession { Instant start; Instant end; } { _id: XYZ, sessions: { {start: XYZ, end: XYZ}, {start: XYZ, end: XYZ}, {start: XYZ, end: XYZ} } } import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.time.Instant; import org.bson.codecs.pojo.annotations.BsonId; import org.bson.codecs.pojo.annotations.BsonProperty; public class User { @BsonId @BsonProperty("_id") UUID id; private List<Session> sessions = new ArrayList<>(); public class Session { Instant start; Instant end; } } CodecProvider codecProvider = PojoCodecProvider.builder() .register(User.class, User.Session.class);This makes sense as every unique sessions belongs directly to a user and with being a nested class I’d be able to access fields of the parent User object from within the Session object.
Hi Sebastian,
Just to clarify, you’re asking about nesting the Session class inside of User ?
Is there a reason not to make the classes both public ?
public class User {
@BsonId
@BsonProperty("_id")
UUID id;
private List<Session> sessions = new ArrayList<>();
}
public class Session {
Instant start;
Instant end;
}
Regards,
Wan
Session class inside of User . If i have two separate classes I cannot do things like this.User.id Session for getting the UUID of the parent User . Having a separate class with a field id in my Session class does not really represent my database layout and that's what POJOs in my opinion are supposed to do. They should represent the model of the database. Furthermore this cannot be handled by standard MongoDB POJO implementation.