封装MongoDB通用Dao

楼主在开发过程中使用mongodb时发现mongodb没有像mybaties-generator那样的工具来生成dao层接口,需要手动实现,感觉有点麻烦,便心血来潮封装了一些常用的增删改查的通用接口。使开发人员使用mongodb开发时更加简单方便。子类dao继承后需指定bean类型。如有错误欢迎大家指正。具体代码如下:
MongodbBaseDao.java:

import com.mongodb.client.result.DeleteResult;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
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.data.util.Pair;
import org.springframework.util.Assert;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.Date;
import java.util.List;

public class MongodbBaseDao {
    @Autowired
    private MongoTemplate mongoTemplate;
    public void insert(T t) {
        mongoTemplate.insert(t);
    }
    public DeleteResult delete(T t){
        return mongoTemplate.remove(t);
    }
    public DeleteResult deleteById(Object id){
        T t = mongoTemplate.findById(id, getTClass());
        return delete(t);
    }
    public DeleteResult delete(Query query){
        return mongoTemplate.remove(query,getTClass());
    }

    public void update(T t) {
       mongoTemplate.save(t);
    }
    public T findById(Object id) {
        return mongoTemplate.findById(id,getTClass());
    }
    public List findAll() {
        return mongoTemplate.findAll(getTClass());
    }
    public List find(Query query){
        return mongoTemplate.find(query,getTClass());
    }

    public boolean exists(Query query){
        return  mongoTemplate.exists(query,getTClass());
    }
    public boolean exists(T t){
        return  exists(getIdQueryFor(t));
    }
    public boolean exitsById(Object id){
        return exists(findById(id));
    }
    public long count(Query query) {
        return mongoTemplate.count(query,getTClass());
    }
    private Class getTClass() {
        Class tClass = (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return tClass;
    }
    private Pair extractIdPropertyAndValue(Object object) {
        Assert.notNull(object, "Id cannot be extracted from 'null'.");
        Class objectType = object.getClass();
        if (object instanceof Document) {
            return Pair.of("_id", ((Document)object).get("_id"));
        } else {
            MongoPersistentEntity entity = (MongoPersistentEntity)mongoTemplate.getConverter().getMappingContext().getPersistentEntity(objectType);
            if (entity != null && entity.hasIdProperty()) {
                MongoPersistentProperty idProperty = (MongoPersistentProperty)entity.getIdProperty();
                return Pair.of(idProperty.getFieldName(), entity.getPropertyAccessor(object).getProperty(idProperty));
            } else {
                throw new MappingException("No id property found for object of type " + objectType);
            }
        }
    }

    private Query getIdQueryFor(Object object) {
        Pair id = this.extractIdPropertyAndValue(object);
        return new Query(Criteria.where((String)id.getFirst()).is(id.getSecond()));
    }


}

子类dao:

@Repository
public class PropertyDao extends MongodbBaseDao<PropertyManage>{

}

sevice层代码:

@Service
public class PropertyServiceImpl implements PropertyService {
    @Autowired
    private PropertyDao propertyDao;

    @Override
    public List list(String application, String key, String profile, String status) {
        Criteria criteria = Criteria.where("id").ne(null);
        if (application != null && application.length() > 0) {
            criteria.and("application").is(application);
        }
        if (key != null && key.length() > 0) {
            criteria.and("key").is(key);
        }
        if (profile != null && profile.length() > 0){
            criteria.and("profile").is(profile);
        }
        if (status != null && status.length() > 0) {
            criteria.and("status").is(Integer.parseInt(status));
        }
        return propertyDao.find(Query.query(criteria));
    }

    @Override
    public boolean modify(PropertyManage propertyManage) {
        propertyDao.update(propertyManage);
        return true;
    }

    @Override
    public boolean delete(String id) {
        return propertyDao.deleteById(id).getDeletedCount() > 0;
    }

    @Override
    public boolean add(PropertyManage propertyManage) {
        propertyDao.insert(propertyManage);
        return true;
    }

    @Override
    public PropertyManage findById(String id) {
        return propertyDao.findById(id);
    }

    @Override
    public boolean eixsts(PropertyManage propertyManage) {
        return propertyDao.exists(propertyManage);
    }

如需转载请标明出处https://blog.csdn.net/u014682892/article/details/82663442,谢谢合作!

你可能感兴趣的:(微服务)