当前位置: 代码迷 >> 综合 >> spring boot mongodb自定义自增id
  详细解决方案

spring boot mongodb自定义自增id

热度:43   发布时间:2024-03-06 13:52:11.0

自定义注解

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoId {
}

自定义监听事件

@Component
public class MongodbAutoIdEvent extends AbstractMongoEventListener<Object> {@AutowiredMongoTemplate mongoTemplate;@Overridepublic void onBeforeConvert(BeforeConvertEvent<Object> event) {Object source = event.getSource();if (null != source) {ReflectionUtils.doWithFields(source.getClass(), new ReflectionUtils.FieldCallback() {@Overridepublic 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 {@Idprivate 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;
}

 

  相关解决方案