我正在使用Mongodb和Spring Boot(1.4.4.RELEASE),我将一个对象存储在MongoDB数据库中,当我尝试使用AggregationOperation获取Object时,我得到一个CodecConfigurationException。
我的MongoDbConfig是
@Configuration
public class MongoDbConfig {
@Value("${mongodb_host}")
private String host;
@Value("${mongodb_port}")
private String port;
@Value("${mongodb_name}")
private String dataBase;
@Value("${mongodb_username}")
private String userName;
@Value("${mongodb_password}")
private String password;
public @Bean MongoClient mongoClient() {
return new MongoClient(new ServerAddress("127.0.0.1", 27017), new ArrayList<MongoCredential>() {
{
add(MongoCredential.createCredential(userName, dataBase,password.toCharArray()));
}
});
}
public @Bean MongoDbFactory mongoDbFactory() throws Exception {
return new SimpleMongoDbFactory(mongoClient(), dataBase);
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory());
return mongoTemplate;
}
}
我的文件是
@Document(collection = "FuelBook")
public class FuelBook implements Serializable {
private String orgId;
private String branchId;
private String vehicleId;
private String driverName;
private DateTime date;
private boolean isActive = true;
private Double kmsReading;
private float costOfFuel;
private String typeOfFuel;
//getter and setter
}
我正在使用以下代码创建文档
public String addFuelBookDetails(AddFuelBookDetailsDTO request,
String orgId, String branchId, String vehicleId) {
try{
if(!mongoTemplate.collectionExists(FuelBook.class)){
mongoTemplate.createCollection(FuelBook.class);
}
FuelBook fuelBook = new FuelBook();
fuelBook.setOrgId(orgId);
fuelBook.setBranchId(branchId);
fuelBook.setVehicleId(vehicleId);
fuelBook.setDriverName(request.getDriverName());
fuelBook.setDate(TimeConversionHelper.getJodaDate(request.getDate(),
"yyyy-MM-dd"));
fuelBook.setCostOfFuel(Float.parseFloat((request.getCostOfFuel())));
fuelBook.setKmsReading(Double.parseDouble(request.getKmsReading()));
fuelBook.setTypeOfFuel(request.getTypeOfFuel());
mongoTemplate.insert(fuelBook, "FuelBook");
return StringConstants.SUCCESS;
} catch(Exception e) {
return null;
}
}
此代码创建String To DateTime
public static DateTime getJodaDate(String dateString, String format) {
DateTime dateTime = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = (Date) sdf.parse(dateString);
long timeInMillis = date.getTime();
dateTime = new DateTime(timeInMillis);
} catch (ParseException e1) {
e1.printStackTrace();
}
return dateTime;
}
使用以下代码尝试获取所有FuelBook
AggregationOperation org = Aggregation.match(Criteria.where("orgId").is(orgId));
AggregationOperation branch = Aggregation.match(Criteria.where("branchId").is(branchId));
AggregationOperation vehicle = Aggregation.match(Criteria.where("vehicleId").is(vehicleId));
DateTime jodaStartTime = TimeConversionHelper.getJodaDate(request.getStartTime(), "yyyy-MM-dd");
DateTime jodaEndTime = TimeConversionHelper.getJodaDate(request.getEndTime(), "yyyy-MM-dd");
AggregationOperation startTime = Aggregation.match(Criteria.where("date").gte(jodaStartTime));
AggregationOperation endTime = Aggregation.match(Criteria.where("date").lte(jodaEndTime));
AggregationOperation offsetAggregation=Aggregation.skip(offset);
AggregationOperation limitAggregation=Aggregation.limit(limit);
Aggregation aggregation = Aggregation.newAggregation(org, branch, vehicle, startTime, endTime,offsetAggregation,limitAggregation);
AggregationResults<FuelBook> result = mongoTemplate.aggregate(aggregation, "FuelBook" ,FuelBook.class);
if(result!=null && result.getMappedResults()!=null && !result.getMappedResults().isEmpty()) {
List<FuelBook> fuelLists = result.getMappedResults();
但是,我遇到了此错误消息:
org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class org.joda.time.DateTime.
at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63)
at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37)
at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:210)
at com.mongodb.DBObjectCodec.encodeMap(DBObjectCodec.java:220)
at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:196)
at com.mongodb.DBObjectCodec.encodeMap(DBObjectCodec.java:220)
at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:196)
at com.mongodb.DBObjectCodec.encodeMap(DBObjectCodec.java:220)
at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:196)
at com.mongodb.DBObjectCodec.encodeIterable(DBObjectCodec.java:269)
at com.mongodb.DBObjectCodec.writeValue(DBObjectCodec.java:198)
at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:128)
at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:61)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
at com.mongodb.connection.RequestMessage.addDocument(RequestMessage.java:253)
at com.mongodb.connection.RequestMessage.addDocument(RequestMessage.java:205)
at com.mongodb.connection.CommandMessage.encodeMessageBodyWithMetadata(CommandMessage.java:75)
at com.mongodb.connection.RequestMessage.encodeWithMetadata(RequestMessage.java:160)
at com.mongodb.connection.CommandProtocol.sendMessage(CommandProtocol.java:184)
at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:108)
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:159)
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:286)
at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:173)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:215)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:186)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:178)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:91)
at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:84)
at com.mongodb.operation.CommandReadOperation.execute(CommandReadOperation.java:55)
at com.mongodb.Mongo.execute(Mongo.java:773)
at com.mongodb.Mongo$2.execute(Mongo.java:760)
at com.mongodb.DB.executeCommand(DB.java:653)
at com.mongodb.DB.command(DB.java:423)
at com.mongodb.DB.command(DB.java:439)
at com.mongodb.DB.command(DB.java:394)
at org.springframework.data.mongodb.core.MongoTemplate$3.doInDB(MongoTemplate.java:390)
at org.springframework.data.mongodb.core.MongoTemplate$3.doInDB(MongoTemplate.java:388)
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:446)
at org.springframework.data.mongodb.core.MongoTemplate.executeCommand(MongoTemplate.java:388)
at org.springframework.data.mongodb.core.MongoTemplate.aggregate(MongoTemplate.java:1556)
at org.springframework.data.mongodb.core.MongoTemplate.aggregate(MongoTemplate.java:1491)
at com.icarat.eshiksha.mongodb.dao.impl.FuelBookDAOImpl.getFuelBookDetails(FuelBookDAOImpl.java:153)
at com.icarat.eshiksha.rest.controller.FuelBookController.getFuelBookDetails(FuelBookController.java:132)
任何人都可以提供一些有关这种情况发生的见解吗?谢谢
答案 0 :(得分:0)
我从this链接
找到了解决方案我在MongoDbConfig中更改我的mongoClient,如
public @Bean MongoClient mongoClient() {
BSON.addEncodingHook(DateTime.class, new JodaTimeTransformer());
BSON.addDecodingHook(Date.class, new JodaTimeTransformer());
return new MongoClient(new ServerAddress("127.0.0.1", 27017), new ArrayList<MongoCredential>() {
{
add(MongoCredential.createCredential(userName, dataBase,password.toCharArray()));
}
});
}
我只是将JodaTimeTransformer类添加到我的项目classPath
中