实际工作中我们有些数据需要存在mongodb的集合中,跟存mysql数据库类型,只不过存mongodb不用新建表,创建集合数据的时候同时创建集合了。
BaseMongoRepository 类,使用Spring Data Repository可以极大地减少数据访问层的代码
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.io.Serializable;
import java.util.List;
/**
* Mongodb 集合操作接口
* @param <T>
* @param <ID>
*/
public interface BaseMongoRepository<T, ID extends Serializable> {
/**
* 根据集合Id查询
* @param id
* @return
*/
T get(ID id);
/**
* 新增集合
* @param param
* @return
*/
T save(T param);
/**
* 新增集合
* @param param
* @param collectionName
* @return
*/
T save(T param, String collectionName);
/**
* 根据id删除集合
* @param id
* @return
*/
long delete(ID id);
/**
* 批量删除集合
* @param ids
* @return
*/
long deleteAll(List<String> ids);
/**
* 根据条件查询,指定类
* @param query
* @param c
* @param <C>
* @return
*/
<C> List<C> find(Query query, Class<C> c);
/**
* 查询所有
* @return
*/
List<T> findAll();
/**
* 根据条件查询
* @param query
* @return
*/
List<T> findByCondition(Query query);
/**
* 根据条件查询,返回第一个
* @param query
* @return
*/
public T findOne(Query query) ;
/**
* 根据条件查询,并排序
* @param query
* @param sort
* @return
*/
List<T> findByCondition(Query query, Sort sort);
/**
* 查询并更新
* @param query
* @param update
* @return
*/
public T findAndModify(Query query, Update update);
/**
* 批量新增
* @param paramList
*/
void insertAll(List<T> paramList);
/**
* 新增集合
* @param param
*/
void insert(T param);
/**
* 根据条件分页查询
* @param query
* @param request
* @return
*/
Page<T> queryByConditionPage(Query query, PageRequest request);
/**
* 根据条件分页查询并排序
* @param query
* @param request
* @param sort
* @return
*/
Page<T> queryByConditionPage(Query query, PageRequest request, Sort sort);
/**
* 根据条件分页查询,排序,指定返回类
* @param query
* @param pageable
* @param sort
* @param c
* @param <C>
* @return
*/
<C> Page<C> queryByConditionPage(Query query, PageRequest pageable, Sort sort, Class<C> c);
/**
* 根据条件分页查询,排序,指定返回类,集合名称
* @param query
* @param pageable
* @param sort
* @param c
* @param collectionName
* @param <C>
* @return
*/
<C> Page<C> queryByConditionPage(Query query, PageRequest pageable, Sort sort, Class<C> c, String collectionName);
/**
* [简要描述]: 通过设置的条件查询,更新符合条件的第一条数据
* [详细描述]:
* @param query :
* @param update :
**/
void updateFirst(Query query, Update update);
/**
* [简要描述]: 通过设置的条件查询,更新符合条件的数据
* [详细描述]:
* @param query :
* @param update :
**/
void update(Query query, Update update);
/**
* [简要描述]: 根据id更新
* [详细描述]:
* @param id :
* @param update :
**/
T updateById(Object id, Update update);
}
BaseMongoRepositoryImpl 类
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
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 java.io.Serializable;
import java.util.List;
/**
* mongodb 集合操作类
* insert: 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException 异常提示主键重复,不保存当前数据。
* save: 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作
*/
public class BaseMongoRepositoryImpl<T, ID extends Serializable> implements BaseMongoRepository<T, ID> {
@Autowired
protected MongoTemplate mongoTemplate;
protected Class<T> repositoryClass = null;
protected String collectionName;
public BaseMongoRepositoryImpl() {
super();
}
public BaseMongoRepositoryImpl(Class<T> t) {
this.repositoryClass = t;
Document document = t.getAnnotation(Document.class);
this.collectionName = document.collection();
}
@Override
public T save(T param) {
mongoTemplate.save(param);
return param;
}
@Override
public T save(T param, String collectionName) {
mongoTemplate.save(param, collectionName);
return param;
}
@Override
public T findAndModify(Query query, Update update) {
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
return mongoTemplate.findAndModify(query, update, options, repositoryClass);
}
@Override
public long deleteAll(List<String> ids) {
DeleteResult result = mongoTemplate.remove(new Query(Criteria.where("_id").in(ids)), repositoryClass);
return result.getDeletedCount();
}
@Override
public long delete(Serializable id) {
DeleteResult result = mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), repositoryClass);
return result.getDeletedCount();
}
@Override
public T get(Serializable id) {
return mongoTemplate.findById(id, repositoryClass);
}
@Override
public <C> List<C> find(Query query, Class<C> c) {
return mongoTemplate.find(query, c, collectionName);
}
@Override
public List<T> findAll() {
return mongoTemplate.findAll(repositoryClass);
}
@Override
public List<T> findByCondition(Query query) {
return mongoTemplate.find(query, repositoryClass);
}
@Override
public T findOne(Query query) {
return mongoTemplate.findOne(query, repositoryClass);
}
@Override
public List<T> findByCondition(Query query, Sort sort) {
query.with(sort);
return mongoTemplate.find(query, repositoryClass);
}
@Override
public void insertAll(List<T> paramList) {
mongoTemplate.insertAll(paramList);
}
@Override
public void insert(T param) {
mongoTemplate.insert(param);
}
@Override
public Page<T> queryByConditionPage(Query query, PageRequest pageable) {
long count = mongoTemplate.count(query, repositoryClass);
query.limit(pageable.getPageSize());
query.skip((long) (pageable.getPageNumber() - 1) * pageable.getPageSize());
List<T> list = mongoTemplate.find(query, repositoryClass);
return new PageImpl<>(list, PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()), count);
}
@Override
public Page<T> queryByConditionPage(Query query, PageRequest pageable, Sort sort) {
long count = mongoTemplate.count(query, repositoryClass);
query.limit(pageable.getPageSize());
query.skip((long) (pageable.getPageNumber() - 1) * pageable.getPageSize());
query.with(sort);
List<T> list = mongoTemplate.find(query, repositoryClass);
return new PageImpl<>(list, PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()), count);
}
@Override
public <C> Page<C> queryByConditionPage(Query query, PageRequest pageable, Sort sort, Class<C> c) {
long count = mongoTemplate.count(query, repositoryClass);
query.limit(pageable.getPageSize());
query.skip((long) (pageable.getPageNumber() - 1) * pageable.getPageSize());
query.with(sort);
List<C> list = mongoTemplate.find(query, c, collectionName);
return new PageImpl<>(list, PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()), count);
}
@Override
public <C> Page<C> queryByConditionPage(Query query, PageRequest pageable, Sort sort, Class<C> c, String collectionName) {
long count = mongoTemplate.count(query, collectionName);
query.limit(pageable.getPageSize());
query.skip((long) (pageable.getPageNumber() - 1) * pageable.getPageSize());
query.with(sort);
List<C> list = mongoTemplate.find(query, c, collectionName);
return new PageImpl<>(list, PageRequest.of(pageable.getPageNumber() - 1, pageable.getPageSize()), count);
}
@Override
public void updateFirst(Query query, Update update) {
mongoTemplate.updateFirst(query, update, repositoryClass);
}
@Override
public void update(Query query, Update update) {
mongoTemplate.updateMulti(query, update, repositoryClass);
}
@Override
public T updateById(Object id, Update update) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(id));
mongoTemplate.updateFirst(query, update, repositoryClass);
return mongoTemplate.findById(id, repositoryClass);
}
}
使用:
我们以用户user信息为例,新增一个UserDocumnet集合,使用@Document注解标识是mongodb集合
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
@Document(collection = "user_document")
public class UserActionLogDocument {
/**
* 主键id
*/
@Id
private String id;
/**
* 用户id
*/
private Long userId;
/**
* 用户登录账号
*/
private String account;
/**
* 用户名称
*/
private String userName;
/**
* mobile
*/
private String mobile;
/**
* address
*/
private String address;
}
再新建用户的Repository继承BaseMongoRepository就可以了
public interface UserRepository extends BaseMongoRepository<UserDocument, String> {
}
再新建RespositoryImpl
@Service
public class UseRepositoryImpl extends BaseMongoRepositoryImpl<UserDocument, String> implements UserRepository {
public UserRepositoryImpl() {
super(UserDocument.class);
}
}
最后在我们需要调用的地方引入这个UserRepository即可
@Autowired
UserRepository userRepository;