0

I have a java class that as the id has an object that holds the actual id value. How can I use Spring Data MongoDB for id generation and identification, and how to define the MongoDB repository?

Example:

@Document
class A {
  @Id
  private B id;

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

This throws exception due to the fact that Spring can't autogenerate value for B class.

2dor
  • 851
  • 3
  • 15
  • 35
  • please refer https://stackoverflow.com/questions/36448921/how-can-we-create-auto-generated-field-for-mongodb-using-spring-boot – dassum Nov 05 '19 at 13:58
  • @dassum sorry but it's not the same thing. In that question the question is how to increment. Mine is more how to use a custom object as the id and how to convert when using the find from the spring data repository. – 2dor Nov 05 '19 at 14:11

1 Answers1

1

Found the solution.

Spring data repository is created in the following way:

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

In order to autogenerate values for B, an event needs to be created:

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);
        }
    }
}
2dor
  • 851
  • 3
  • 15
  • 35