本文共 3317 字,大约阅读时间需要 11 分钟。
cmsPageRepository是继承了MongoRepository<T, ID>的接口
//添加@Testpublic void testInsert(){ //定义实体类 CmsPage cmsPage = new CmsPage(); cmsPage.setSiteId("s01"); cmsPage.setTemplateId("t01"); cmsPage.setPageName("测试页面"); cmsPage.setPageCreateTime(new Date()); ListcmsPageParams = new ArrayList<>(); CmsPageParam cmsPageParam = new CmsPageParam(); cmsPageParam.setPageParamName("param1"); cmsPageParam.setPageParamValue("value1"); cmsPageParams.add(cmsPageParam); cmsPage.setPageParams(cmsPageParams); cmsPageRepository.save(cmsPage); System.out.println(cmsPage);}
//删除@Testpublic void testDelete() { cmsPageRepository.deleteById("5b17a2c511fe5e0c409e5eb3");}
关于Optional:
Optional是jdk1.8引入的类型,Optional是一个容器对象,它包括了我们需要的对象,使用isPresent方法判断所包 含对象是否为空,isPresent方法返回false则表示Optional包含对象为空,否则可以使用get()取出对象进行操作。 Optional的优点是://修改@Testpublic void testUpdate() { Optionaloptional = cmsPageRepository.findOne("5b17a34211fe5e2ee8c116c9");if(optional.isPresent()){ CmsPage cmsPage = optional.get();cmsPage.setPageName("测试页面01");cmsPageRepository.save(cmsPage);}}
同Spring Data JPA一样Spring Data mongodb也提供自定义方法的规则,如下:
按照findByXXX,findByXXXAndYYY、countByXXXAndYYY等规则定义方法,实现查询操作。public interface CmsPageRepository extends MongoRepository{ //根据页面名称查询 CmsPage findByPageName(String pageName); //根据页面名称和类型查询 CmsPage findByPageNameAndPageType(String pageName,String pageType); //根据站点和页面类型查询记录数 int countBySiteIdAndPageType(String siteId,String pageType); //根据站点和页面类型分页查询 Page findBySiteIdAndPageType(String siteId,String pageType, Pageable pageable);}
//从0开始int page = 0;int size = 10;//定义分页对象Pageable pageable = PageRequest.of(page, size).first();//查询所有进行分页,可以使用自定义方法代替,但是自定义形参中必须有PageablePageall = cmsPageRepositoty.findAll(pageable);System.out.println(all);
//从0开始int page = 0;int size = 10;//定义分页参数Pageable pageable = PageRequest.of(page, size).first();//条件值对象,一般为集合的实体对象CmsPage cmspage = new CmsPage();//设置要查询的站点id(精确查询),直接设置值的情况下是精确匹配//cmspage.setSiteId("5a751fab6abb5044e0d19ea1");//设置模板id条件(精确查询)//cmspage.setTemplateId("5a962b52b00ffc514038faf7");//设置页码别名cmspage.setPageAliase("轮播");//定义条件匹配器/*ExampleMatcher exampleMatcher = ExampleMatcher.matching();//针对pageAliase进行修改匹配为模糊匹配exampleMatcher=exampleMatcher.withMatcher("pageAliase",ExampleMatcher.GenericPropertyMatchers.contains());*///简写,并且更加容易更多针对其他字段的匹配器ExampleMatcher exampleMatcher=ExampleMatcher.matching() .withMatcher("pageAliase",ExampleMatcher.GenericPropertyMatchers.contains());//ExampleMatcher.GenericPropertyMatchers.contains();//包含关键字(模糊匹配)//ExampleMatcher.GenericPropertyMatchers.startsWith();//前缀匹配,其他的更加调用方法名,即可理解//定义ExampleExampleexample = Example.of(cmspage, exampleMatcher);//调用查询所有Page all = cmsPageRepositoty.findAll(example, pageable);//转换为List并打印List content = all.getContent();System.out.println(content);
字段
匹配方式spring: data: mongodb: uri: mongodb://127.0.0.1:27017 database: mongodb
转载地址:http://anilf.baihongyu.com/