MongoDB新增Long型主键:抽象基类

假如不想创建自定义注解,也可以直接通过一个继承类,最关键这个类里可以定义一些自己想要的字段和方法,比如加一个更新的时间戳,或者一些DAO层方法等

package com.lihuia.demo.entity;

import org.springframework.data.annotation.Id;

public abstract class MongoBaseDO<T extends Number> {

@Id
private T id;

public T getId() {
return this.id;
}

public void setId(T id) {
this.id = id;
}
}

这个类id字段添加主键注解

这样,实体类就不需要定义主键id字段了,直接继承基类即可

package com.lihuia.demo.entity;

import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;


@Document(collection = "user_center")
@Data
public class User extends MongoBaseDO<Long> {

@Field
private String name;

@Field
private Integer age;

@Field
private String phone;
}

注册子类,覆盖onBeforeConvert方法,拦截对象转换,同样获取自定义主键后再写入

package com.lihuia.demo.util;

import com.lihuia.demo.entity.MongoBaseDO;
import com.lihuia.demo.entity.SeqInfo;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.event.AbstractMongoEventListener;
import org.springframework.data.mongodb.core.mapping.event.BeforeConvertEvent;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class InsertEventListener extends AbstractMongoEventListener<MongoBaseDO> {

@Resource
private MongoTemplate mongoTemplate;

@Override
public void onBeforeConvert(BeforeConvertEvent<MongoBaseDO> event) {
MongoBaseDO source = event.getSource();
Long id = getNextId(source.getClass().getSimpleName());
source.setId(id);
}


private Long getNextId(String collectionName) {
Query query = new Query(Criteria.where("collectionName").is(collectionName));
Update update = new Update();
/** 主键递增1,设置为Long型 */
update.inc("seqId", 1L);
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
/** 原子操作,修改并返回 */
SeqInfo seqInfo = mongoTemplate.findAndModify(query, update, options, SeqInfo.class);
return seqInfo.getSeqId();
}
}

实体对象写入mongodb之前,会注册发布BeforeConvertEvent事件,这里创建了InsertEventListener监听器监听这个事件,拦截后,生成自增主键,配置到实体对象当中

发表评论