Spring Data MongoDB标识符作为对象

我有一个Java类,它的id作为对象具有保存实际id值的对象。如何使用Spring Data MongoDB进行ID生成和标识,以及如何定义MongoDB存储库?

示例:

@Document
class A {
  @Id
  private B id;

}
class B{
 private String id;
 private String idAppGenerator;
}

由于Spring无法自动生成B类的值,因此引发了异常。

slayerwlt1 回答:Spring Data MongoDB标识符作为对象

找到了解决方案。

Spring数据存储库是通过以下方式创建的:

@Repository
public interface ARepository extends MongoRepository<A,B>{
//B is the object identity
}

为了自动生成B的值,需要创建一个事件:

Component
public class IdentifierListener extends AbstractMongoEventListener<A> {

    @Override
    public void onBeforeConvert(BeforeConvertEvent<A> event){
        if(event.getSource().getId() == null){
            B id = new B();
            id.setId(new ObjectId());
            event.getSource().setId(id);
        }
    }
}
本文链接:https://www.f2er.com/3159113.html

大家都在问