springboot简单操作MongoDB——-增删改查
1.引入依赖
- <!--MongoDB starter-->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-mongodb</artifactId>
- </dependency>
2.在配置文件中进行配置
application.properties配置数据源
- spring.data.mongodb.host=xxx.xxx.xxx.xxx
- spring.data.mongodb.port=xxxxxx
- spring.data.mongodb.database=xxxxx
- spring.data.mongodb.username=xxxx
- spring.data.mongodb.password=xxxxx
1.建立实体类。
-
- /**
- * @Date: 2018/8/28 21:22
- * @Description:
- */
-
- @Data
- @Document("Entry") // 声明文档为Entry
- public class Entry {
-
-
- private String id;
-
- private String name;
-
- private Integer age;
-
- private String remark;
-
- 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 Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
-
- public String getRemark() {
- return remark;
- }
-
- public void setRemark(String remark) {
- this.remark = remark;
- }
- }
springBoot2.3 使用MongoRepository整合mongoDb。
创建Dao接口
继承MongoRepository接口,第一个泛型是document文档对象,第二个参数是id的类型,一般直接设置为String类型就行了,让mongo自动生成id
- @Repository
- public interface EntryDao extends MongoRepository<Entry, String> {
-
- }
Service接口
- /**
- * 使用mongoRepository接口,基本能够完成增删改查操作,包括批量插入,批量修改,模糊查询,删除所有,删除满足条件的;
- * 查询满足任一条件的数据,查询满足所有条件的数据;分页查询;查询结果排序
- */
- public interface EntryService {
-
- /**
- * 新增,插入(不能插入相同id的数据)
- * @param po
- * @return
- */
- Entry insertEntry(Entry po);
-
- /**
- * 修改,如果id存在则修改,如果id不存在则新增
- * @param po
- * @return
- */
- Entry updateEntry(Entry po);
-
- /**
- * 插入多条
- * @param EntryList
- * @return
- */
- List<Entry> insertManyEntry(List<Entry> EntryList);
-
- /**
- * 查询一条(即使是有多条数据也只是返回第一条)
- * @param po
- * @return
- */
- EntryfindEntry(Entry po);
-
- /**
- * 查询多条数据
- * @param po
- * @return
- */
- List<Entry> findEntryList(Entry po);
-
- /**
- * 查询结果排序
- * @param po
- * @return
- */
- List<Entry> findEntryListSort(Entry po);
-
- /**
- * 查询满足任意一个条件的多条数据
- * @param po
- * @return
- */
- List<Entry> findEntryListAny(Entry po);
-
- /**
- * 模糊查询
- * @param po
- * @return
- */
- List<Entry> findEntryListLike(Entry po);
-
- /**
- * 模糊查询2
- * @param po
- * @return
- */
- List<Entry> findEntryListLike2(Entry po);
-
- /**
- * 分页查询
- * @param po
- * @return
- */
- Page<Entry> findEntryListByPage(Entry po, int page, int size);
-
- /**
- * 删除所有
- */
- void deleteAll();
-
- /**
- * 根据id删除
- * @param id
- */
- void deleteById(String id);
-
- /**
- * 判断是否存在
- * @param po
- * @return
- */
- Boolean exists(Entry po);
- }
ServiceImpl 实现类
-
- @Service
- public class EntryServiceImpl implements EntryService {
-
- @Autowired
- private EntryDao entrydao;
-
- @Override
- public Entry insertEntry(Entry po) {
- // 新增
- return entrydao.insert(po);
- }
-
- @Override
- public Entry updateEntry(Entry po) {
- // 如果不存在则新增,存在则修改
- return entrydao.save(po);
- }
-
- @Override
- public List<Entry> insertManyEntry(List<Entry> EntryList) {
- return entrydao.insert(EntryList);
- }
-
- @Override
- public Entry findEntry(Entry po) {
- Example<Entry> of = Example.of(po);
- Optional<Entry> one = entrydao.findOne(of);
- return one.get();
- }
-
- @Override
- public List<Entry> findEntryList(Entry po) {
- // Example.of(po) 默认就是 ExampleMatcher.matching() 匹配模式
- return entrydao.findAll(Example.of(po));
- }
-
- @Override
- public List<Entry> findEntryListSort(Entry po) {
- // 构造排序器,按title字段降序排列,如果有多个字段则,分别按多个字段的进行降序
- Sort sort = Sort.by(Sort.Direction.DESC,"title");
- return entrydao.findAll(Example.of(po), sort);
- }
-
- @Override
- public List<Entry> findEntryListAny(Entry po) {
- // 设置为或模式,默认是且模式,或表示查询条件中的任意一个条件满足都返回。是指不同的查询字段,而不是同一个字段的不同值
- ExampleMatcher matcher = ExampleMatcher.matchingAny();
- Example<Entry> example = Example.of(po, matcher);
- return entrydao.findAll(example);
- }
-
- @Override
- public List<Entry> findEntryListLike(Entry po) {
- // 设置不同字段的查询方式:模糊查询
- // 必须是ExampleMatcher.matching().withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())的方式写,
- // 不能分开写成ExampleMatcher matcher = ExampleMatcher.matching(); matcher.withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
- // 因为源码中就说了This instance is immutable and unaffected by this method call。
- // title字段 以包含方式查询,即sql中的 like '%关键词%'
- // description字段以查询结尾的方式查询,即sql中的 like '%关键词'
- // 测试1:"title"
- ExampleMatcher matcher = ExampleMatcher.matching()
- .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
- .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());
-
- // 测试2: 不写title时,默认应该是精确查询的
- /*ExampleMatcher matcher = ExampleMatcher.matching()
- .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());*/
- Example<Entry> example = Example.of(po, matcher);
- return entrydao.findAll(example);
- }
-
- public List<Entry> findEntryListLike2(Entry po) {
- // 改变默认字符串匹配方式:直接把精确查询改为模糊查询
- // 必须是ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);的方式写,
- // 不能分开写成ExampleMatcher matcher = ExampleMatcher.matching(); matcher.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
-
- ExampleMatcher matcher = ExampleMatcher.matching()
- .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
-
- Example<Entry> example = Example.of(po, matcher);
-
- return entrydao.findAll(example);
- }
-
- @Override
- public Page<Entry> findEntryListByPage(Entry po, int page, int size) {
- // 改为模糊查询
- ExampleMatcher matcher = ExampleMatcher.matching()
- .withMatcher("title", ExampleMatcher.GenericPropertyMatchers.contains())
- .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());
-
- // 测试2: 不写title时,默认应该是精确查询的
- /*ExampleMatcher matcher = ExampleMatcher.matching()
- .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.endsWith());*/
- Example<Entry> example = Example.of(po, matcher);
- // 构造分页对象,带排序规则
- // Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "title");
- // 不带排序规则
- Pageable pageable = PageRequest.of(page, size);
- // 分页查询
- return entrydao.findAll(example, pageable);
- }
-
- @Override
- public void deleteAll() {
- entrydao.deleteAll();
-
- }
-
- @Override
- public void deleteById(String id) {
- entrydao.deleteById(id);
- }
-
- @Override
- public Boolean exists(Entry po) {
- return entrydao.exists(Example.of(po));
- }
- }
测试
日志使用lombok, 测试工具使用SpringBootTest
-
- @Slf4j
- @SpringBootTest
- public class EntryTest {
- @Autowired
- private EntryService entryService;
-
- @Test
- public void testInsertEntry() {
- Entry po = new Entry();
- // 有没有这个setId都可以,如果不设置则由mongodb自动生成一个id
- // po.setId("1");
- po.setTitle("今日大事件2");
- po.setDescription("今日大事件的描述2");
- Entry Entry = entryService.insertEntry(po);
- log.info("【新增话术】Entry:{}", Entry);
- }
-
- @Test
- public void testUpdateEntry() {
- Entry po = new Entry();
- po.setTitle("今日大事件3");
- Entry Entry = entryService.findEntry(po);
- Entry.setDescription("今日大事件3修改了呀2");
- EntryService.updateEntry(Entry);
- log.info("【修改话术】Entry:{}", Entry);
- }
-
- @Test
- public void testInsertManyEntry() {
- List<Entry> list = new ArrayList<>();
- for (int i = 0; i < 20; i++) {
- Entry po = new Entry();
- po.setTitle("今日热榜" + i);
- po.setDescription("今日热榜描述A" + i);
- list.add(po);
- }
- List<Entry> Entryes = entryService.insertManyEntry(list);
- log.info("【新增话术】Entry:{}", Entryes);
- }
-
- @Test
- public void testFindEntry() {
- Entry po = new Entry();
- po.setTitle("今日大事件2");
- Entry Entry = entryService.findEntry(po);
- log.info("【查询话术】Entry:{}", Entry);
- }
-
- @Test
- public void testFindEntryList() {
- Entry po = new Entry();
- po.setTitle("今日大事件2");
- List<Entry> EntryList = entryService.findEntryList(po);
- log.info("【查询话术】Entry:{}", EntryList);
- }
-
- @Test
- public void testFindEntryListByPage() {
- Entry po = new Entry();
- po.setTitle("今日热榜");
- Page<Entry> EntryListByPage = entryService.findEntryListByPage(po, 0, 10);
- int totalPages = EntryListByPage.getTotalPages();
- List<Entry> content = EntryListByPage.getContent();
- int number = EntryListByPage.getSize();
- int numberOfElements = EntryListByPage.getNumberOfElements();
- log.info("【分页查询话术】totalPage:{} number:{} , numberOfElements:{}, Entry:{}, ", totalPages, number,numberOfElements, content);
- }
-
- @Test
- public void testFindEntryListSort() {
- Entry po = new Entry();
- // po.setTitle("今日大事件2");
- List<Entry> EntryList = entryService.findEntryListSort(po);
- log.info("【话术查询结果排序】Entry:{}", EntryList);
- }
-
- @Test
- public void testFindEntryListAny() {
- Entry po = new Entry();
- po.setTitle("今日大事件2");
- po.setDescription("今日大事件的描述3");
- List<Entry> EntryList = entryService.findEntryListAny(po);
- log.info("【话术查询或】Entry:{}", EntryList);
- }
-
- @Test
- public void testFindEntryListLike() {
- Entry po = new Entry();
- po.setTitle("大事件3");
- // po.setDescription("3修改了呀2");
- // po.setTitle("今日大事件3");
- List<Entry> EntryList = entryService.findEntryListLike(po);
- log.info("【话术模糊查询】Entry:{}", EntryList);
- }
-
- @Test
- public void testFindEntryListLike2() {
- Entry po = new Entry();
- po.setTitle("大");
- po.setDescription("3");
- // po.setTitle("今日大事件3");
- List<Entry> EntryList = entryService.findEntryListLike2(po);
- log.info("【话术模糊查询】Entry:{}", EntryList);
- }
-
- @Test
- public void testDeleteAll() {
- EntryService.deleteAll();
- }
-
- @Test
- public void testDeleteById() {
- Entry po = new Entry();
- po.setTitle("今日大事件2");
- Entry Entry = entryService.findEntry(po);
- EntryService.deleteById(Entry.getId());
- log.info("【删除】Entry:{}", Entry);
- }
-
- @Test
- public void testExists() {
- Entry po = new Entry();
- po.setTitle("今日大事件3");
- Boolean exist = entryService.exists(po);
- log.info("【判断是否存在】:{}", exist);
- }
- }
使用MongoTemplate进行简单的增删改查
-
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.boot.test.context.SpringBootTest;
- 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.test.context.junit4.SpringRunner;
-
- import java.util.List;
-
- /**
- * @Date: 2018/8/28 21:30
- * @Description:
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class EntryTest {
-
- /**
- * 直接注入mongoTemplate即可使用
- * */
- private MongoTemplate mongoTemplate;
-
- //增
- @Test
- public void add(Entry entry){
- entry.setId("1");
- entry.setName("张三");
- entry.setAge(15);
- entry.setRemark("喜欢打球、喜欢喝茶");
- //存储操作
- mongoTemplate.save(entry);
- //指定集合名
- mongoTemplate.save(entry,"人员表");
- }
-
- //删除
- @Test
- public void delete(String id){
- mongoTemplate.remove("1");
- mongoTemplate.remove("1","人员表");
- Query query = new Query();
- //拼装删除数据
- query.addCriteria(Criteria.where("id").is("1"));
- mongoTemplate.remove(query,"人员表");
- mongoTemplate.remove(query,Entry.class);
- }
- //改
- @Test
- public void edit(Entry entry){
- Query query = new Query(Criteria.where("id").is(entry.getId()));
- //拼装修改数据
- Update update = new Update();
- update.set("name","李四");
- update.set("remark","喜欢画画");
- mongoTemplate.updateFirst(query, update, Entry.class);
- }
-
-
- //简单查
- @Test
- public void query(String id){
- //单条
- Query query = new Query(Criteria.where("id").is(id));//可累加条件
- Entry entrY = mongoTemplate.findOne(query,Entry.class);
- //多条
- Query query2 = new Query(Criteria.where("remark").regex("喜欢"));//可累加条件
- List<Entry> entries = mongoTemplate.find(query, Entry.class);
- }
-
-
- //查询所有
- @Test
- public void findAll(){
- List<Entry> entries = mongoTemplate.find(Entry.class);
- }
-
- //根据id查询
- @Test
- public void findById(Integer id){
- Query query=new Query(Criteria.where("_id").is(id));//可累加条件
- Entry student = mongoTemplate.findOne(query, Entry.class);
- }
-
- }
分页查询——此处我写了两个工具类
-
- import org.springframework.data.domain.Sort;
-
- import java.io.Serializable;
-
- /**
- * @Auther:
- * @Date: 2018/8/22 08:48
- * @Description:
- * @Version: 1.0
- */
- public class MongoDBPageModel implements Serializable {
- /**
- * @Fields: serialVersionUID
- * @Todo: TODO
- */
- private static final long serialVersionUID = 1L;
- // 当前页
- private Integer pagenumber = 1;
- // 当前页面条数
- private Integer pagesize = 10;
- // 排序条件
- private Sort sort;
- public Integer getPagenumber() {
- return pagenumber;
- }
- public void setPagenumber(Integer pagenumber) {
- this.pagenumber = pagenumber;
- }
- public Integer getPagesize() {
- return pagesize;
- }
- public void setPagesize(Integer pagesize) {
- this.pagesize = pagesize;
- }
- public Sort getSort() {
- return sort;
- }
- public void setSort(Sort sort) {
- this.sort = sort;
- }
-
- }
-
- import java.io.Serializable;
- import org.springframework.data.domain.Pageable;
- import org.springframework.data.domain.Sort;
- /**
- * @Auther:
- * @Date: 2018/8/22 10:19
- * @Description:
- * @Version: 1.0
- */
- public class SpringbootMongoDBPageable implements Serializable,Pageable{
- /**
- * @Fields: serialVersionUID
- * @Todo: TODO
- */
- private static final long serialVersionUID = 1L;
-
- MongoDBPageModel page;
-
- public MongoDBPageModel getPage() {
- return page;
- }
-
- public void setPage(MongoDBPageModel page) {
- this.page = page;
- }
-
- @Override
- public Pageable first() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public int getOffset() {
- // TODO Auto-generated method stub
- return (page.getPagenumber() - 1) * page.getPagesize();
- }
-
- @Override
- public int getPageNumber() {
- // TODO Auto-generated method stub
- return page.getPagenumber();
- }
-
- @Override
- public int getPageSize() {
- // TODO Auto-generated method stub
- return page.getPagesize();
- }
-
-
- @Override
- public boolean hasPrevious() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public Pageable next() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Pageable previousOrFirst() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Sort getSort() {
- // TODO Auto-generated method stub
- return page.getSort();
- }
- }
分页查询+分页聚合查询(多表多条件关联分页查询+结果集解析)——-依然测试类
-
- /**
- * @Date: 2018/8/28 21:30
- * @Description:
- */
- @RunWith(SpringRunner.class)
- @SpringBootTest
- public class EntryTest {
-
- /**
- * 直接注入mongoTemplate即可使用
- * */
- private MongoTemplate mongoTemplate;
-
- //分页查询
- @Test
- public void PageQuery(){
- //利用工具类拼装分页信息
- SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
- MongoDBPageModel pm=new MongoDBPageModel();
- pm.setPagesize(3);
- pm.setPagenumber(1);
- List<Order> orders = new ArrayList<>(); //排序信息
- orders.add(new Order(Direction.DESC, "age"));
- Sort sort = new Sort(orders);
- pm.setSort(sort);
- pageable.setPage(pm);
- //拼装查询信息
- Query query = new Query();
- Criteria criteria = new Criteria();
- query.addCriteria(criteria.where("age").gte(6).lte(18));//检索6-18岁的
- query.addCriteria(criteria.where("name").regex("文"));//模糊查询名字
- Long count = mongoTemplate.count(query, OrdersData.class);//查询总记录数
- List<Entry> list = mongoTemplate.find(query.with(pageable), Entry.class);
- }
- //分页聚合查询(多表多条件关联分页查询)
- @Test
- public void PageQuery2(){
- //mongodb中有两个表,一个是人物表 一个是宠物表,一个人可以有多个宠物
- //人物表字段为 String id, Integer age,String remark;
- //宠物表字段为 String id, String manId,String age,String remark;
- //拼装分页信息
- SpringbootMongoDBPageable pageable = new SpringbootMongoDBPageable();
- MongoDBPageModel pm=new MongoDBPageModel();
- pm.setPagesize(2);
- pm.setPagenumber(1);
- List<Order> orders = new ArrayList<>(); //排序
- orders.add(new Order(Direction.DESC, "age"));
- Sort sort = new Sort(orders);
- pm.setSort(sort);
- pageable.setPage(pm);
-
- //拼装关联信息
- LookupOperation lookupOperation = LookupOperation.newLookup().
- from("dogData").//关联表名
- localField("_id").//关联字段
- foreignField("manId").//主表关联字段对应的次表字段
- as("dogs");//查询结果集合名
-
- //拼装具体查询信息
- //次表
- Criteria ordercri = Criteria.where("dogs").not().size(0);//只查询有宠物的人
- ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation match = Aggregation.match(ordercri);
- //主表
- Criteria qqq=Criteria.where("name").regex("文");//只查询名字中带有文的人
- AggregationOperation match1= Aggregation.match(qqq);
-
- //分页查询
- Aggregation aggregation = Aggregation.newAggregation(match1,lookupOperation,match,Aggregation.sort(pageable.getSort()),//排序
- Aggregation.skip(pageable.getPageNumber()>1?(pageable.getPageNumber()-1)*pageable.getPageSize():0),//pagenumber
- Aggregation.limit(pageable.getPageSize()));//pagesize
- //总数查询
- Aggregation counts = Aggregation.newAggregation(match1,lookupOperation,match).;
- int count = mongoTemplate.aggregate(counts, "manEntry", BasicDBObject.class).getMappedResults().size();
- List<BasicDBObject> results = mongoTemplate.aggregate(aggregation, "manEntry", BasicDBObject.class).getMappedResults();
- //查询出的结果集为BasicDBObject类型
- //解析过程
- for (BasicDBObject b :results
- ) {
- //转化为jsonobject对象
- JSONObject jsonObject = new JSONObject(b);
- String id = jsonObject.get("id").toString();
- Integer age = ((int) jsonObject.get("age"));
- String remark = jsonObject.get("remark").toString();
- //转化为jsonarray
- JSONArray dogs = jsonObject.getJSONArray("dogs");
- if (dogs.size() > 0) {
- for (int i = 0; i < dogs.size(); i++) {
- JSONObject job = dogs.getJSONObject(i);
- String dogId = job.get("id").toString();
- String manId = job.get("manId").toString();
- }
- }
-
- }
- }
-
-
- }
4.在Controller中进行引入
- @Autowired
- private MongoTemplate mongoTemplate;
带条件查询
- Query query = new Query();
- if (code!=0) {
- query.addCriteria(Criteria.where("buiness_core").is(code));//is:等于
- }
- // query.fields().exclude("details.details");//exclude:不需要查询这个字段
- List<Station> list = mongoTemplate.find(query, 对应实体类的名称.class);//fin:查询集合中所有的对象
多表联查
- /**
- * 两表联查
- *
- * @return
- */
- @GetMapping("/DeviceAndStation")
- public Object findStudentAndGrade(String stationId){
- LookupOperation lookupOperation=LookupOperation.newLookup().
- from("t_wlw_station"). //关联从表名
- localField("station_id"). //主表关联字段
- foreignField("_id").//从表关联的字段
- as("DeviceAndStation"); //查询结果名
- //带条件查询可以选择添加下面的条件
-
- Aggregation aggregation=Aggregation.newAggregation(lookupOperation);
- List<Map> results = mongoTemplate.aggregate(aggregation,"t_device", Map.class).getMappedResults();
- //上面的student必须是查询的主表名
- System.out.println(JSON.toJSONString(results));
- return results;
- }
分页查询
后端代码:
- @Override
- public Page<StrategyComment> queryPage(StrategyCommentQuery qo) {
- // totalPage prePage nextPage
- Query query = new Query();
- Criteria criteria = new Criteria();
- if (qo.getStrategyId() != null) {
- criteria = Criteria.where("strategyId").in(qo.getStrategyId());
- query.addCriteria(criteria);
- }
- // 模糊匹配
- if (qo.getKeyword() != null) {
- String keyword = qo.getKeyword();
- String pattern = ".*" + keyword + ".*"; // 正则表达式
- criteria.orOperator(Criteria.where("strategyTitle").regex(pattern),Criteria.where("content").regex(pattern));// 多条件模糊查询
- query.addCriteria(criteria);
- }
- // totalCount
- long totalCount = mongoTemplate.count(query, StrategyComment.class);
- // 如果没数据,可以优化性能不用继续执行了
- if (totalCount == 0) {
- return Page.empty();
- }
- // data
- // 第一个参数 从 0 开始
- Sort orderBy = Sort.by(Sort.Direction.DESC, "createTime"); //倒序
- Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),orderBy);
- query.with(pageable);
- List<StrategyComment> data = mongoTemplate.find(query, StrategyComment.class);
- // 三个参数 List<T> content, Pageable pageable, long total
- return new PageImpl<StrategyComment>(data, pageable, totalCount);
- }
前端代码:
- <div th:fragment="mongoPage" style="text-align: center;">
- <ul id="pagination" class="pagination"></ul>
- <script>
- //分页
- $(function () {
- var totalPages = [[${page.totalPages}]]
- var startPage = [[${page.pageable.pageNumber}+1]]
-
- $("#pagination").twbsPagination({
- totalPages: totalPages || 1,
- startPage: startPage || 1,
- visiblePages: 5,
- first: "首页",
- prev: "上页",
- next: "下页",
- last: "尾页",
- initiateStartPageClick: false,
- onPageClick: function (event, page) {
- $("#currentPage").val(page);
- $("#searchForm").submit();
- }
- });
- })
- </script>
- </div>
多表联查
- @Test
- public void saveMany() {// 批处理(10万条数据1127)(100万条条数据测试75773)qps13197
- Long startTime = System.currentTimeMillis();
- List<Aqz> aqzList = new ArrayList<>();
- for (int i = 0; i < 1000000; i++) {
- Aqz aqz = new Aqz();
- int random = (int) (Math.random() * 2);
- aqz.setABoolean(random == 0 ? false : true);
- aqz.setCreateDate(new Date());
- aqz.setString("string2" + i);
- aqz.setAnInt(i + 20000);
- aqz.setADouble(Math.random() * 2);
- List list = new ArrayList<>();
- list.add("aaa2" + i);
- list.add("bbb2" + i);
- list.add("ccc2" + i);
- aqz.setList(list);
- aqzList.add(aqz);
- System.out.println(i);
- }
- mongoTemplate.insertAll(aqzList);
-
- Long endtTime = System.currentTimeMillis();
- Long resultTime = endtTime - startTime;
- System.out.println("[总共执行耗时]" + resultTime);
-
- }
- ###分页,范围,模糊,排序###########################################################@Test
- public void saveClazz() {// 添加课堂
- Clazz clazz = new Clazz();
- clazz.setClazzName("天天课堂3");
- mongoTemplate.insert(clazz);
- }
-
- @Test
- public void saveStudent() {// 添加学生
- String clazzName = "天天课堂";
- Query query = new Query(Criteria.where("clazzName").is(clazzName));
- Clazz clazz = mongoTemplate.findOne(query, Clazz.class);
- Student student = new Student();
- student.setStudentName("小红2");
- student.setAge(18);
- student.setClazzId(clazz.getId());
- mongoTemplate.save(student);
-
- }
-
- @Test
- public void findOneClazz() {
- Query query = new Query(Criteria.where("_id").is("60e10203d31e2641ecb748ee"));
- Clazz clazz = mongoTemplate.findOne(query, Clazz.class);
- // clazz】】】" + clazz);
- }
- @Test
- public void findByManyStudent1() {// 多条件1
- Query query = new Query();
- query.addCriteria(Criteria.where("studentName").is("小红"));
- query.addCriteria(Criteria.where("age").is(18));
- List
students = mongoTemplate.find(query, Student.class); - // students);
- }
- @Test
- public void findByManyStudent0() {// 多条件0
- Query query = new Query(Criteria.where("studentName").is("小红"));
- query.addCriteria(Criteria.where("age").is(18));
- List
students = mongoTemplate.find(query, Student.class); - // students);
- }
- @Test
- public void findByManyStudent3() {// 多条件3
- Query query = new Query(Criteria.where("studentName").is("小红").and("age").is(18));
- List
students = mongoTemplate.find(query, Student.class); - // students);
- }
- @Test
- public void findByManyStudent2() {// 多条件2
- Student student = new Student();
- student.setStudentName("小红");
- student.setAge(18);
- Query query = new Query(Criteria.byExample(student));
- List
students = mongoTemplate.find(query, Student.class); - // students);
- }
- @Test
- public void findByManyStudentOr() {// 多条件0 or
- Query query = new Query(Criteria.where("studentName").regex("小"));
- query.addCriteria(new Criteria().orOperator(Criteria.where("age").is(18),
- new Criteria().andOperator(Criteria.where("studentName").is("小明"), Criteria.where("age").is(16))));
- List
students = mongoTemplate.find(query, Student.class); - // students);
- }
- @Test
- public void searchClazzByIn() {// in操作
- List
str = new ArrayList<>(); - str.add("天天课堂");
- Query query = new Query(Criteria.where("name").in(str));
- List
clazzList = mongoTemplate.find(query, Clazz.class); - // clazzList】】】" + clazzList);
-
- }
-
- @Test
- public void findListStudentSort() {// 排序
- Query query = new Query();
- query.with(Sort.by(Sort.Direction.DESC, "age"));
- List<Student> students = mongoTemplate.find(query, Student.class);
- // students】】】" + students);
- }
- @Test
- public void findFenYeList() {// 分页
- // 设置分页参数
- Query query = new Query();
- int currentPage = 2;// 0,1相同
- int pageSize = 2;
- // 设置分页信息
- query.limit(pageSize);
- query.skip(pageSize * (currentPage - 1));
- // query.addCriteria(Criteria.where("clazzName").regex("天"));
- List
clazzes = mongoTemplate.find(query, Clazz.class); - // clazzs】】】" + clazzes);
- }
-
- @Test
- public void update() {// 更新
- Query query = Query.query(Criteria.where("id").is("60e103fcd31e2615bcaf91ed"));// 添加查询条件
- // query.addCriteria(Criteria.where("time").gte(beginTime).lte(endTime));
- Update update = new Update();
- update.set("clazzName", "111");
- UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Clazz.class);
- // updateResult.toString());
-
- }
-
- @Test
- public void delete() {// 删除
- Query query = Query.query(Criteria.where("id").is("60e103fcd31e2615bcaf91ed"));
- mongoTemplate.remove(query, Clazz.class);
- }
-
- @Test
- public void findZongHe() {// 分页+范围+模糊查询+排序
- // 拼装查询信息
- Query query = new Query();
- query.addCriteria(Criteria.where("age").gte(6).lte(18));
- query.with(Sort.by(Sort.Direction.ASC, "age"));
- query.addCriteria(Criteria.where("name").regex("小"));
- // 模糊查询名字
- Long count = mongoTemplate.count(query, Student.class);
- // 查询总记录数
- List<Student> list = mongoTemplate.find(query, Student.class);
-
- }
- ####分组,两表三表联查###########################################################
- import com.csw.mongodbspringbootdemo.entity.Chair;
- import com.csw.mongodbspringbootdemo.entity.Desk;
- import com.csw.mongodbspringbootdemo.entity.Room;
- import com.mongodb.BasicDBObject;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import org.springframework.data.domain.Sort;
- import org.springframework.data.mongodb.core.MongoTemplate;
- import org.springframework.data.mongodb.core.aggregation.Aggregation;
- import org.springframework.data.mongodb.core.aggregation.AggregationOperation;
- import org.springframework.data.mongodb.core.aggregation.AggregationResults;
- import org.springframework.data.mongodb.core.aggregation.LookupOperation;
- import org.springframework.data.mongodb.core.query.Criteria;
- import org.springframework.data.mongodb.core.query.Query;
- import org.springframework.test.context.junit4.SpringRunner;
-
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.UUID;
-
- @SpringBootTest
- @RunWith(SpringRunner.class)
- public class RoomDeskRecommend {
- @Autowired
- private MongoTemplate mongoTemplate;
-
- @Test
- public void saveRoom() {// 添加房间
- Room room = new Room();
- room.setName("空房间2");
- room.setUnitCode(UUID.randomUUID().toString());
- mongoTemplate.save(room);
- Room room2 = new Room();
- room2.setName("空房间1");
- room2.setUnitCode(UUID.randomUUID().toString());
- mongoTemplate.save(room2);
-
- }
-
- @Test
- public void saveDesk() {// 添加桌子
- String roomName = "光明房间";
- String deskName = "5号桌子";
- Query query = new Query(Criteria.where("name").is(roomName));
- Room room = mongoTemplate.findOne(query, Room.class);
- Desk desk = new Desk();
- desk.setName(deskName);
- assert room != null;
- desk.setUnitCode(room.getUnitCode());
- mongoTemplate.save(desk);
- System.out.println(room);
-
- Query query2 = new Query(Criteria.where("name").is(deskName));
- Desk desk2 = mongoTemplate.findOne(query2, Desk.class);
- System.out.println(desk2);
-
- }
-
- @Test
- public void groupBy() {// group
- List<AggregationOperation> aggs = new ArrayList<>();
- // aggs.add(Aggregation.match(Criteria.where("name").is("log")));
- aggs.add(Aggregation.group("name").count().as("count"));
- aggs.add(Aggregation.project().and("_id").as("name").and("count").as("count"));
-
- Aggregation agg = Aggregation.newAggregation(aggs);
-
- AggregationResults<Map> results = mongoTemplate.aggregate(agg, Desk.class, Map.class);
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- @Test
- public void findMoreTable() {// 两表联查
-
- LookupOperation lookupOperation = LookupOperation.newLookup().from("room"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("rooms");// 查询结果集合名
- Criteria ordercri = Criteria.where("rooms").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi = Aggregation.match(ordercri);
- Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi);// 排序
- List<Map> results = mongoTemplate.aggregate(aggregation, "desk", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- @Test
- public void findMoreTable2() {// 两表联查
-
- LookupOperation lookupOperation = LookupOperation.newLookup().from("desk"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("desks");// 查询结果集合名
-
- Criteria ordercri = Criteria.where("desks").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi = Aggregation.match(ordercri);
- Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi);// 排序
- List<Map> results = mongoTemplate.aggregate(aggregation, "room", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- @Test
- public void findMoreTableZongHe() {// 两表联查
-
- int pageNumber = 2;// 0,1相同
- int pageSize = 2;
- // 拼装关联信息
- LookupOperation lookupOperation = LookupOperation.newLookup().from("room"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("ClazzStudents");// 查询结果集合名
- // 拼装具体查询信息
- // 次表
- Criteria ordercri = Criteria.where("ClazzStudents").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi = Aggregation.match(ordercri);
- // 主表
- Criteria qqq = Criteria.where("name").regex("号");// 只查询名字中带有文的人
- AggregationOperation matchFu = Aggregation.match(qqq);
- // 分页查询
- Aggregation aggregation = Aggregation.newAggregation(matchFu, lookupOperation, matchZi,
- Aggregation.sort(Sort.Direction.DESC, "name"),
- Aggregation.skip(pageSize > 1 ? (pageNumber - 1) * pageSize : 0), Aggregation.limit(pageSize));// 排序
- // Aggregation.skip(pageable.getPageNumber()>1?(pageable.getPageNumber()-1)*pageable.getPageSize():0),//pagenumber
- // 分页
- /*
- * Aggregation.skip(pageSize>1?(pageNumber-1)*pageSize:0);
- * Aggregation.limit(pageSize);
- */
- // Aggregation.group("name");
-
- // 总数查询
- Aggregation counts = Aggregation.newAggregation(matchFu, lookupOperation, matchZi);
- int count = mongoTemplate.aggregate(counts, Desk.class, BasicDBObject.class).getMappedResults().size();
- System.out.println("【count】" + count);
- List<Map> results = mongoTemplate.aggregate(aggregation, "desk", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- /*
- * public PageResult
pagination(Class clazz, int pageSize, int pageNum, - * Query query) { long total = this.mongoTemplate.count(query, clazz); Integer
- * pages = (int)Math.ceil((double)total / (double)pageSize); if (pageNum <= 0 ||
- * pageNum > pages) { pageNum = 1; } int skip = pageSize * (pageNum - 1);
- * query.skip(skip).limit(pageSize); List
list = mongoTemplate.find(query, - * clazz); PageResult pageResult = new PageResult(); pageResult.setTotal(total);
- * pageResult.setPages(pages); pageResult.setPageSize(pageSize);
- * pageResult.setPageNum(pageNum); pageResult.setList(list); return pageResult;
- * }
- */
- @Test
- public void saveChair() {// 添加椅子
- String roomName = "光明房间";
- String chairName = "1号椅子";
- Query query = new Query(Criteria.where("name").is(roomName));
- Room room = mongoTemplate.findOne(query, Room.class);
- Chair chair = new Chair();
- chair.setName(chairName);
- assert room != null;
- chair.setUnitCode(room.getUnitCode());
- mongoTemplate.save(chair);
-
- }
-
- @Test
- public void findMoreTable3_0() {// 三表联查测试,第一个表关联第二个人表(关联字段1),第一个表关联第三个表(关联字段1)
-
- LookupOperation lookupOperation = LookupOperation.newLookup().from("desk"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("desks");// 查询结果集合名
-
- Criteria ordercri = Criteria.where("desks").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi = Aggregation.match(ordercri);
- LookupOperation lookupOperation2 = LookupOperation.newLookup().from("chair"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("chairs");// 查询结果集合名
-
- Criteria ordercri2 = Criteria.where("chairs").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi2 = Aggregation.match(ordercri2);
- Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi, lookupOperation2, matchZi2);// 排序
- List<Map> results = mongoTemplate.aggregate(aggregation, "room", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- // 数据模拟
- @Test
- public void findMoreTable3_1() {// 三表联查测试,第一个表关联第二个人表(关联字段1),第一个表关联第三个表(关联字段2)
-
- LookupOperation lookupOperation = LookupOperation.newLookup().from("desk"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("desks");// 查询结果集合名
-
- Criteria ordercri = Criteria.where("desks").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi = Aggregation.match(ordercri);
- LookupOperation lookupOperation2 = LookupOperation.newLookup().from("chair"). // 关联表名
- localField("lastCode"). // 主关联字段
- foreignField("lastCode").// 从表关联字段对应的次表字段
- as("chairs");// 查询结果集合名
-
- Criteria ordercri2 = Criteria.where("chairs").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi2 = Aggregation.match(ordercri2);
- Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi, lookupOperation2, matchZi2);// 排序
- List<Map> results = mongoTemplate.aggregate(aggregation, "room", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- // 数据模拟
- @Test
- public void findMoreTable3_3() {// 三表联查测试,第一个表关联第二个人表(关联字段1),第二个表关联第三个表(关联字段2)
- LookupOperation lookupOperation = LookupOperation.newLookup().from("room"). // 关联表名
- localField("unitCode"). // 主关联字段
- foreignField("unitCode").// 从表关联字段对应的次表字段
- as("rooms");// 查询结果集合名
-
- Criteria ordercri = Criteria.where("rooms").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi = Aggregation.match(ordercri);
- LookupOperation lookupOperation2 = LookupOperation.newLookup().from("chair"). // 关联表名
- localField("rooms.lastCode"). // 主关联字段
- foreignField("lastCode").// 从表关联字段对应的次表字段
- as("chairs");// 查询结果集合名
-
- Criteria ordercri2 = Criteria.where("chairs").not().size(0);// 只查询有宠物的人
- // ordercri.and("age").gte(1).lte(5);//只查询1岁到5岁的宠物
- AggregationOperation matchZi2 = Aggregation.match(ordercri2);
- Aggregation aggregation = Aggregation.newAggregation(lookupOperation, matchZi, lookupOperation2, matchZi2);// 排序
- List<Map> results = mongoTemplate.aggregate(aggregation, "desk", Map.class).getMappedResults(); // 查询出的结果集为BasicDBObject类型
- for (Map result : results) {
- System.out.println(result);
- }
- }
-
- }