Home > AI > Database > MongoDB >

Mongo @Id

In my experience, I’ve come across various formats for the @Id annotation.

Form 1

@Id 
private String id;

In this scenario, you have the option to manually assign the ID, providing you with complete control.

Alternatively, if you choose not to, the system will automatically generate an ObjectId(…) in the MongoDB database.

Form 2

@Id 
private Long id;

Form 3

@Id 
private ObjectId id;

Form 4, id will auto-increment.

@Id
@AutoIncKey
private Long id;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIncKey {

}


@Component
@RequiredArgsConstructor
public class MNMongoAutoIncListener extends AbstractMongoEventListener<Object> {

    private final MongoTemplate mongo;

    @Override
    public void onBeforeConvert(BeforeConvertEvent<Object> event) {
        final Object source = event.getSource();
        if (source != null) {
            ReflectionUtils.doWithFields(source.getClass(),new ReflectionUtils.FieldCallback(){
                @Override
                public void doWith(Field field)throws IllegalArgumentException, IllegalAccessException {
                    ReflectionUtils.makeAccessible(field);
                    if (field.isAnnotationPresent(AutoIncKey.class)) {
                        field.set(source, getNextAutoId(source.getClass().getSimpleName()));
                    }
                }
            });
        }
    }



    private Long getNextAutoId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));
        Update update = new Update();
        update.inc("seqId", 1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.upsert(true);
        options.returnNew(true);
        SeqInfo seq = mongo.findAndModify(query, update, options, SeqInfo.class);
        assert seq != null;
        return seq.getSeqId();
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
public class SeqInfo {

    @Id
    private String id;

    @Field
    private String collName;

    @Field
    private Long seqId;

}

Leave a Reply