SpringBoot之集成MongoDB
Posted zengnansheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot之集成MongoDB相关的知识,希望对你有一定的参考价值。
环境 SpringBoot2.0
增加maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
yml增加配置
spring:
data:
mongodb:
uri: mongodb://user1:[email protected]:27017/test_db
实体类
import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.io.Serializable; import java.util.Date; @Document(collection = "t_book") public class Book implements Serializable @Id private String id; //名称 private String name; //所属分类 private String categoryId; //价格 private Integer price; //出版时间 private Date publishTime; public String getId() return id; public void setId(String id) this.id = id; public String getName() return name; public void setName(String name) this.name = name; public String getCategoryId() return categoryId; public void setCategoryId(String categoryId) this.categoryId = categoryId; public Integer getPrice() return price; public void setPrice(Integer price) this.price = price; public Date getPublishTime() return publishTime; public void setPublishTime(Date publishTime) this.publishTime = publishTime;
简单测试
@RestController @RequestMapping("/mongodbTest") public class MongodbTestController @Autowired private MongoDBUtil mongoDBUtil; @RequestMapping("/insert") public void insert() for (int i = 1; i < 100; i++) Book book = new Book(); book.setName("book" + i); book.setCategoryId("1"); book.setPrice(i); book.setPublishTime(new Date()); mongoDBUtil.insert(book); @RequestMapping("/find") public List<Book> find() Book book = new Book(); book.setCategoryId("1"); List<Book> list = mongoDBUtil.find(book, Book.class); return list;
附上简单常用的MongoDBUtil
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; 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 java.lang.reflect.Field; import java.util.Collection; import java.util.List; @Component public class MongoDBUtil @Autowired private MongoTemplate mongoTemplate; /** * 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作 * * @param obj */ public void save(Object obj) mongoTemplate.save(obj); /** * 若新增数据的主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException * insert: 可以一次性插入一整个列表,而不用进行遍历操作,效率相对较高 save: 需要遍历列表,进行一个个的插入 * * @param obj */ public void insert(Object obj) mongoTemplate.insert(obj); /** * 批量插入 * * @param collection */ public void insertAll(Collection<? extends Object> collection) mongoTemplate.insertAll(collection); /** * 修改匹配到的第一条记录 * * @param query * @param update * @param entityClass */ public void updateFirst(Query query, Update update, Class<?> entityClass) mongoTemplate.updateFirst(query, update, entityClass); /** * 修改匹配到的所有记录 * * @param query * @param update * @param entityClass */ public void updateMulti(Query query, Update update, Class<?> entityClass) mongoTemplate.updateMulti(query, update, entityClass); /** * 修改匹配到的记录,若不存在该记录则进行添加 * * @param query * @param update * @param entityClass */ public void upsert(Query query, Update update, Class<?> entityClass) mongoTemplate.upsert(query, update, entityClass); /** * 根据id删除 * * @param id * @param entityClass */ public void deleteById(Object id, Class<?> entityClass) Query query = new Query(Criteria.where("_id").is(id)); mongoTemplate.remove(query, entityClass); /** * 根据查询条件删除 * * @param query * @param entityClass */ public void delete(Query query, Class<?> entityClass) mongoTemplate.remove(query, entityClass); /** * 根据id判断是否存在 * * @param id * @param entityClass * @return */ public boolean exists(String id, Class<?> entityClass) Query query = Query.query(Criteria.where("_id").is(id)); return exists(query, entityClass); /** * 根据查询条件判断是否存在 * * @param query * @param entityClass * @return */ public boolean exists(Query query, Class<?> entityClass) return mongoTemplate.exists(query, entityClass); /** * 根据查询对象查询 * * @param obj * @param entityClass * @param <T> * @return */ public <T> List<T> find(Object obj, Class<T> entityClass) Query query = getQueryByObject(obj); return mongoTemplate.find(query, entityClass); /** * 根据查询对象查询 返回单个 * * @param obj * @param entityClass * @param <T> * @return */ public <T> T findOne(Object obj, Class<T> entityClass) Query query = getQueryByObject(obj); return mongoTemplate.findOne(query, entityClass); /** * 查询所有 * * @param entityClass * @param <T> * @return */ public <T> List<T> findAll(Class<T> entityClass) return mongoTemplate.findAll(entityClass); /** * 根据id查询 * * @param id * @param entityClass * @param <T> * @return */ public <T> T findById(Object id, Class<T> entityClass) return mongoTemplate.findById(id, entityClass); /** * 根据多个ids查询 * * @param ids * @param entityClass * @param <T> * @return */ public <T> List<T> findByIds(Object[] ids, Class<T> entityClass) Query query = Query.query(Criteria.where("_id").in(ids)); return mongoTemplate.find(query, entityClass); /** * 分页查询 * * @param obj * @param pageIndex 分页索引从1开始 * @param pageSize * @param entityClass * @param <T> * @return */ public <T> List<T> getPage(Object obj, int pageIndex, int pageSize, Class<T> entityClass) Query query = getQueryByObject(obj); int start = (pageIndex - 1) * pageSize; query.skip(start); query.limit(pageSize); return this.mongoTemplate.find(query, entityClass); /** * 根据查询条件统计个数 * * @param query * @param entityClass * @return */ public Long getCount(Query query, Class<?> entityClass) return this.mongoTemplate.count(query, entityClass); /** * 根据查询对象统计个数 * * @param obj * @param entityClass * @return */ public Long getCount(Object obj, Class<?> entityClass) Query query = getQueryByObject(obj); return this.mongoTemplate.count(query, entityClass); //将查询条件对象转换为query private Query getQueryByObject(Object object) Query query = new Query(); Criteria criteria = new Criteria(); Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) Object filedValue; try if ("serialVersionUID".equals(fields[i].getName())) continue; fields[i].setAccessible(true); filedValue = fields[i].get(object); if (filedValue != null) criteria.and(fields[i].getName()).is(filedValue); catch (IllegalArgumentException e) e.printStackTrace(); catch (IllegalAccessException e) e.printStackTrace(); query.addCriteria(criteria); return query; //将查询条件对象转换为update private Update getUpdateByObject(Object object) Update update = new Update(); Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) Object filedValue; try if ("serialVersionUID".equals(fields[i].getName())) continue; fields[i].setAccessible(true); filedValue = fields[i].get(object); if (filedValue != null) update.set(fields[i].getName(), filedValue); catch (IllegalArgumentException e) e.printStackTrace(); catch (IllegalAccessException e) e.printStackTrace(); return update; public void addTag(Object id, String tagName, Object obj, Class<?> entityClass) Query query = Query.query(Criteria.where("_id").is(id)); Update update = new Update(); update.addToSet(tagName, obj); mongoTemplate.upsert(query, update, entityClass);
以上是关于SpringBoot之集成MongoDB的主要内容,如果未能解决你的问题,请参考以下文章