Spring Data MongoDB:动态字段名称转换器



如何动态设置 MongoDB 文档字段名称(不使用 @Field (?

@Document
public class Account {
    private String username;
}

例如,字段名称应大写。结果:

{"USERNAME": "hello"}

我希望这个动态转换器适用于任何文档,因此是不使用泛型的解决方案。

这有点奇怪的要求。您可以使用 Mongo 侦听器生命周期事件文档。

@Component
public class MongoListener extends AbstractMongoEventListener<Account> {
  @Override
  public void onBeforeSave(BeforeSaveEvent<Account> event) {
     DBObject dbObject = event.getDBObject();
     String username = (String) dbObject.get("username");// get the value
     dbObject.put("USERNAME", username);
     dbObject.removeField("username");
     // You need to go through each and every field recursively in  
     // dbObject and then remove the field and then add the Field you  
     // want(with modification) 
  }
}

这有点笨拙,但我相信没有干净的方法可以做到这一点。

最新更新