Вопрос довольно простой, как мне заставить MongoTemplate.findOne получать полный объект.
Мой класс сущности User ниже.
Код: Выделить всё
@Document(collection = "users")
@Data
@ToString
public class User {
@MongoId(targetType = FieldType.OBJECT_ID)
private String id;
@Size(max = 20)
@NotBlank
private String username;
@NotBlank
@Size(max = 50)
@Email
private String email;
@NotBlank
private String passwordHash;
private Set roles = new HashSet();
private Profile profile;
private Date createdAt;
private Date updatedAt;
public User() {
this.createdAt = new Date();
this.updatedAt = new Date();
}
public User(String username, String email, String passwordHash, String firstName, String lastName, String bio, String profilePicture) {
this.profile = new Profile(firstName, lastName, bio, profilePicture);
this.username = username;
this.email = email;
this.passwordHash = passwordHash;
this.createdAt = new Date();
this.updatedAt = new Date();
}
public User(String username, String email, String passwordHash) {
this.username = username;
this.email = email;
this.passwordHash = passwordHash;
this.createdAt = new Date();
this.updatedAt = new Date();
}
public User(String username, String email, String passwordHash, Profile profile) {
this(username, email, passwordHash);
this.profile = profile;
}
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public static class Profile {
@Size(max = 50)
@NotBlank
private String firstName;
@Size(max = 50)
@NotBlank
private String lastName;
@Size(max = 300)
private String bio;
private String profilePicture;
}
}
Код: Выделить всё
public Optional findByUsername(String username) {
Query query = new Query();
query.addCriteria(Criteria.where("username").is(username));
query.fields()
.include("username")
.include("email")
.include("createdAt")
.include("roles")
.include("passwordHash")
.include("profile");
Optional user = Optional.ofNullable(mongoTemplate.findOne(query, User.class));
return user;
}
Буду благодарен за любую помощь. Я обдумывал это, пробовал и GenAI, но безуспешно.
Если требуется какой-либо другой фрагмент кода, дайте мне знать.
Подробнее здесь: https://stackoverflow.com/questions/791 ... edded-json
Мобильная версия