MongoDB、Spring Data、findAll()メソッドエラー:
タイプ[Java.lang.String]からタイプ[Java.time.LocalDateTime]に変換できるコンバーターが見つかりませんでした
public class EntityName {
@Id
private String id;
private Map<LocalDateTime, Integer> statistic;
}
エンティティを保存できますが、ロードできません。簡単な修正はありますか?
これで問題は解決しました。
@Configuration
public class MongoConfiguration extends AbstractMongoConfiguration {
@Value("${spring.data.mongodb.database:test}")
private String database;
@Value("${spring.data.mongodb.Host:localhost}:${spring.data.mongodb.port:27017}")
private String Host;
@Autowired
private MappingMongoConverter mongoConverter;
// Converts . into a mongo friendly char
@PostConstruct
public void setUpMongoEscapeCharacterConversion() {
mongoConverter.setMapKeyDotReplacement("_");
}
@Override
protected String getDatabaseName() {
return database;
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient(Host);
}
@Bean
@Override
public CustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new MongoLocalDateTimeFromStringConverter());
return new CustomConversions(converterList);
}
private static final class MongoLocalDateTimeFromStringConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
return source == null ? null : LocalDateTime.parse(source);
}
}
}
@Maksymのやり方も私を助けてくれました。 Spring Framework5とSpringBoot2用に少し調整する必要がありました。
@Bean
@Primary
public MappingMongoConverter mongoConverter(
@Autowired MongoMappingContext mongoMappingContext,
@Autowired MongoDbFactory mainMongoFactory,
@Autowired MongoCustomConversions conversions
) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mainMongoFactory);
MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
mongoConverter.setMapKeyDotReplacement("#");
mongoConverter.afterPropertiesSet();
mongoConverter.setCustomConversions(conversions);
return mongoConverter;
}
@Bean
public MongoMappingContext mongoMappingContext() {
MongoMappingContext context = new MongoMappingContext();
context.setSimpleTypeHolder(new SimpleTypeHolder(new HashSet<>(Arrays.asList(
DateTime.class,
LocalDateTime.class
)), MongoSimpleTypes.HOLDER));
return context;
}
@Bean
public MongoCustomConversions customConversions() {
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new MongoLocalDateTimeFromStringConverter());
converterList.add(new MongoDateTimeFromStringConverter());
return new MongoCustomConversions(converterList);
}
private static final class MongoLocalDateTimeFromStringConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String source) {
return source == null ? null : LocalDateTime.parse(source);
}
}
private static final class MongoDateTimeFromStringConverter implements Converter<String, DateTime> {
@Override
public DateTime convert(String source) {
return source == null ? null : DateTime.parse(source);
}
}