自定义注解
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface AutoId { }自定义监听事件
@Component public class MongodbAutoIdEvent extends AbstractMongoEventListener<Object> { @Autowired MongoTemplate mongoTemplate; @Override public void onBeforeConvert(BeforeConvertEvent<Object> event) { Object source = event.getSource(); if (null != source) { ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); if (field.isAnnotationPresent(AutoId.class)) { field.set(source, getNextId(source.getClass().getSimpleName())); } } }); } super.onBeforeConvert(event); } private Long getNextId(String collectionName) { Query query = new Query(Criteria.where("collectioin_name").is(collectionName)); Update update = new Update(); update.inc("aid", 1); FindAndModifyOptions options = new FindAndModifyOptions(); options.upsert(true); options.returnNew(true); CollectionId collectionId = mongoTemplate.findAndModify(query, update, options, CollectionId.class); return collectionId.getAid(); } }
创建一个集合用于保存自增id与集合的关系
@Document(collection = "collection_id") @TableName("collection_id") public class CollectionId { private String id; @Field("collectioin_name") private String collectionName; private Long aid; // 自增id }
使用,为了同时使用mongodb自己的id,方便增删改查,我使用了aid用于保存自增id
@Document(collection = "tacct") @TableName("tacct") public class Tacct { @Id private String id; @AutoId @Field("aid") private Long tacctId; @Field("nick_name") private String nickName; @Field("user_type") private Long userType; @Field("update_time") private Long updateTime; private transient Broker objUserType; }