Spring 数据 MongoDB 作为对象的标识符
Spring Data MongoDB identifier as object
我有一个 java class 因为 id 有一个包含实际 id 值的对象。如何使用 Spring 数据 MongoDB 生成和识别 ID,以及如何定义 MongoDB 存储库?
示例:
@Document
class A {
@Id
private B id;
}
class B{
private String id;
private String idAppGenerator;
}
由于 Spring 无法为 B class.
自动生成值,因此抛出异常
找到解决方案。
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);
}
}
}
我有一个 java class 因为 id 有一个包含实际 id 值的对象。如何使用 Spring 数据 MongoDB 生成和识别 ID,以及如何定义 MongoDB 存储库?
示例:
@Document
class A {
@Id
private B id;
}
class B{
private String id;
private String idAppGenerator;
}
由于 Spring 无法为 B class.
自动生成值,因此抛出异常找到解决方案。
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);
}
}
}