我正在尝试为Spring Data Mongo实现一个@WritingConverter,但似乎什么也没做。
我尝试了以下这篇文章:https://www.baeldung.com/spring-data-mongodb-index-annotations-converter。
还尝试在其他StackOverflow线程中找到答案:
Spring not using mongo custom converters;
Spring data MongoDb: MappingMongoConverter remove _class;
Spring Mongodb - Cannot write custom Converter for java.time.Period;
Setup custom converters in Spring Data Mongo;
我使用的是MongoRepository(例如JPARepository),而不是mongoTemplate来获取查询结果。
这是我要转换的班级:
@Document(collection = "users")
@Getter
@Setter
public class User {
@Id
private int id;
private String username;
private String password;
private String role;
private PersonalData personalData;
public User() {
}
@PersistenceConstructor
public User(String username, String password, String role, PersonalData personalData) {
this.username = username;
this.password = password;
this.role = role;
this.personalData = personalData;
}
}
这是MongoConfig类:
@Configuration
@EnableMongoRepositories(basePackages = {"edu.utcn.carappapi.repositories"})
public class MongoConfig extends AbstractMongoConfiguration {
private List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>();
@Override
protected String getDatabaseName() {
return "rentcar";
}
@Override
public MongoClient mongoClient() {
return new MongoClient("127.0.0.1", 27017);
}
// @Override
// public MappingMongoConverter mappingMongoConverter() throws Exception {
// DbRefResolver dbRefResolver = new DefaultDbRefResolver(this.mongoDbFactory());
// MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, this.mongoMappingContext());
// converter.setCustomConversions(this.customConversions());
// converter.afterPropertiesSet();
// return converter;
// }
@Override
public MongoCustomConversions customConversions() {
converters.add(new UserWriterConverter());
return new MongoCustomConversions(converters);
}
}
这是WritingConverter:
@Component
@WritingConverter
public class UserWriterConverter implements Converter<User, DBObject> {
@Override
public DBObject convert(User user) {
DBObject dbObject = new BasicDBObject();
dbObject.put("id", user.getId());
dbObject.put("username", "dummy");
dbObject.put("password", user.getPassword());
dbObject.put("role", user.getRole());
if (user.getPersonalData() != null) {
DBObject personalDataDbObject = new BasicDBObject();
personalDataDbObject.put("email", user.getPersonalData().getEmail());
personalDataDbObject.put("firstName", user.getPersonalData().getFirstName());
personalDataDbObject.put("lastName", user.getPersonalData().getLastName());
personalDataDbObject.put("phoneNumber", user.getPersonalData().getPhoneNumber());
personalDataDbObject.put("age", user.getPersonalData().getAge());
dbObject.put("personalData", personalDataDbObject);
}
dbObject.removeField("_class");
return dbObject;
}
}
文档中不应包含_class字段。
{
...
"_class" : "edu.utcn.carappapi.entities.User"
}