在springboot项目中访问mongodb的

来源:互联网 发布:火炬之光2mac 版汉化 编辑:程序博客网 时间:2024/06/01 08:07


由于项目中用到基于springboot项目和mongodb进行交互.所以总结下几种访问方式.

一,继承 MongoRepository 这个接口.

public interface DailyUserActiRepository extends MongoRepository<DailyUserActives,String>{
    public List<DailyUserActives> findByAppid(String appid);


}


1,分页.两个参数,第一个是页码,第二个是页面大小.

    public Page<DailyUserActives> queryAllByPage(int pageIndex, int pageSize) {
        PageRequest pageRequest=new PageRequest(pageIndex-1,pageSize);
        return this.dailyUserActiRepository.findAll(pageRequest);
    }

ps :将Page<DailyUserActives> 转化为 List<DailyUserActives>可以使用Page的 getContent()



2,根据实体类中的属性进行查询:


        当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By + 属性名(首字母大写),如:根据appid查询DailyUserActives


        它会自动根据appid查询。


        public List<DailyUserActives> findByAppid(String appid) {


        return this.dailyUserActiRepository.findByAppid(appid);
    }


        若根据其他属性查询,方法类似!




3,查询所有的数据:
        public List<DailyUserActives> queryAll() {
        return dailyUserActiRepository.findAll();
    }


4,查询所有的数据的数量:
        public int count(){
        long size = dailyUserActiRepository.count();
        int count = Integer.valueOf(String.valueOf(size));
        return count;
    }    


5,根据实体类中的属性进行模糊查询:
        当需要根据实体类中的属性进行模糊查询时,我们也需要在 DailyUserActiRepository 仓库中定义方法,模糊查询定义方法名的规则为:find + By + 属性名(首字母大写) + Like,如:根据姓名进行模糊查询 DailyUserActives
        仓库中添加的方法:
        public List<DailyUserActives> findByCountryLike(String country);
        service中的方法:
        在service中直接调用仓库中我们刚才定义的方法即可!
        public List<DailyUserActives> findByCountryLike(String country){
        return dailyUserActiRepository.findByNameLike(country);
    }
 6, 根据实体类中的属性进行模糊查询带分页:
        带分页的模糊查询,其实是把模糊查询以及分页进行合并,同时我们也需要在 DailyUserActiRepository 仓库中定义方法,定义方法名的规则和模糊查询的规则一致,只是参数不同而已。
        仓库中添加的方法:
        public Page<DailyUserActives> findByCountryLike(String country,Pageable pageable);
        在service中对仓库中的方法的调用:
        public List<DailyUserActives> queryByNameAndPage(int page, int rows, String country)
        {
        PageRequest pageRequest = new PageRequest(page-1,rows);
        
        return dailyUserActiRepository.findByNameLike(country, pageRequest).getContent();
    }   


7,根据实体类中的属性进行模糊查询带分页,同时指定返回的键(数据库中的key,实体类中的属性):切记,无论如何,_id一直会返回的.
        解释一下什么是指定返回的键:也就是说当我们进行带分页的模糊查询时,不想返回数据库中的所有字段,只是返回一部分字段。例如:只返回Person中的id和name,不返回age.
        若想指定返回的键,我们需要在PersonRepository中添加方法,同时使用注解@Query。
        仓库中定义的方法:
        @Query(value="{'country':?0}",fields="{'name':1}")
    public Page<DailyUserActives> findByNameLike(String name,Pageable pageable);
        其中value是查询的条件,?0这个是占位符,对应着方法中参数中的第一个参数,如果对应的是第二个参数则为?1。fields是我们指定的返回字段,其中id是自动返回的,不用我们指定,bson中{'name':1}的1代表true,也就是代表返回的意思。
        在service中对仓库中的方法的调用:
        public List<DailyUserActives> queryByNameAndPage(int page, int rows, String country)
            throws Exception {
        PageRequest pageRequest = new PageRequest(page-1,rows);        
        return dailyUserActiRepository.findByNameLike(country, pageRequest);
    }    




8,查询所有数据,指定返回字段


        当我们需要查询所有数据,同时需要指定返回的键时,则不能使用仓库中自带的findAll()方法了。我们可以查询所有id不为空的数据,同时指定返回的键。当我们需要根据一个key且该key不为空进行查询,方法名的定义规则为:find + By + 属性名(首字母大写) + NotNull。
        仓库中定义的方法:
        @Query(value="{'_id':{'$ne':null}}",fields="{'name':1}")
        public Page<DailyUserActives> findByIdNotNull(Pageable pageable);
        service中调用仓库中的方法:
        public List<DailyUserActives> queryAll(int page, int rows) throws Exception {
        PageRequest pageRequest = new PageRequest(page-1,rows);    
        return personRepository.findByIdNotNull(pageRequest).getContent();
    }


9,扩展 :java中的仓库定义的方法名的规则列举如下,使用时将仓库中方法上的注解@Query中的value进行适当泰欧正即可。
        GreaterThan(大于) 
        方法名举例:findByAgeGreaterThan(int age) 
        query中的value举例:{"age" : {"$gt" : age}}


        LessThan(小于) 
        方法名举例:findByAgeLessThan(int age) 
        query中的value举例:{"age" : {"$lt" : age}}


        Between(在...之间) 
        方法名举例:findByAgeBetween(int from, int to)  
        query中的value举例:{"age" : {"$gt" : from, "$lt" : to}}


        Not(不包含) 
        方法名举例:findByNameNot(String name)
        query中的value举例:{"age" : {"$ne" : name}}


        Near(查询地理位置相近的) 
        方法名举例:findByLocationNear(Point point) 
        query中的value举例:{"location" : {"$near" : [x,y]}} 



       特别注意:

       以下是配置文件:

        application.properties

         spring.data.mongodb.uri=mongodb://SGTraker:SG2dTr4ak6erDc@120.26.3.182:27017,120.26.4.12:27017/prodata?replicaSet=sgmongocluster
         spring.data.mongodb.database=prodata

       

        MongoConfiguration.java如下:

@Configuration
public class MongoConfiguration {
   @Bean
   public MongoDatabase mongoDatabase(MongoClient mongoClient, MongoProperties mongoProperties) {
       return mongoClient.getDatabase(mongoProperties.getDatabase());
   }
}


二,使用MongoTemplate 进行操作.


public interface UserDao {
    public void saveUser(UserEntity userEntity);


    public UserEntity findUserByUserName(String userName);


    public int updateUser(UserEntity userEntity);


    public void deleteUserById(Long id);


    public List<UserEntity> findByConditon();
}


@Component
public class UserDaoImpl implements UserDao{


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void saveUser(UserEntity userEntity) {
        this.mongoTemplate.save(userEntity);
    }


    @Override
    public UserEntity findUserByUserName(String userName) {
        Query query=new Query(Criteria.where("userName").is(userName));
        UserEntity userEntity=this.mongoTemplate.findOne(query,UserEntity.class);
        return userEntity;
    }


    @Override
    public int updateUser(UserEntity userEntity) {
        Query query=new Query(Criteria.where("id").is(userEntity.getId()));
        Update update=new Update().set("userName",userEntity.getUserName()).set("passWord",userEntity.getPassWord());
        WriteResult writeResult=this.mongoTemplate.updateFirst(query,update,UserEntity.class);
        if (null!=writeResult){
            return writeResult.getN();
        }else {
            return 0;
        }
    }


    @Override
    public void deleteUserById(Long id) {
        Query query=new Query(Criteria.where("id").is(id));
        this.mongoTemplate.remove(query,UserEntity.class);


    }


    @Override
    public List<UserEntity> findByConditon() {
//        Query query=new Query(Criteria.where("score").elemMatch(Criteria.where("score").gte(10).lte(100)));
        Query query=new Query(Criteria.where("passWord").is("ziwen123"));
        query.with(new Sort(Sort.Direction.ASC,"userName"));
        query.fields().include("userName");
        query.fields().include("score");
        query.fields().include("passWord");
        query.limit(1);
        return this.mongoTemplate.find(query,UserEntity.class);
    }


}   


ps:


    application.properties

   spring.data.mongodb.host=127.0.0.1
   spring.data.mongodb.port=27017
   spring.data.mongodb.database=test


MongoConfiguration.java如下:

@Configuration
public class MongoConfiguration {
   @Bean
   public MongoDatabase mongoDatabase(MongoClient mongoClient, MongoProperties mongoProperties){
       return mongoClient.getDatabase(mongoProperties.getDatabase());
   }
}


三,直接操作数据库,里面有些聚合操作.

    @GetMapping("actives1")
    public ResponseEntity getActives1(@RequestParam(value = "appIds", required = false) String appIds,
                                      @RequestParam(value = "groupBy", defaultValue = "appid,date") String groupBy,
                                      @RequestParam(value = "startDate") String startDate,
                                      @RequestParam(value = "endDate") String endDate) throws ParseException {
        Bson id=extractGroupById(groupBy);
        Bson match=extractMatch(startDate,endDate,appIds);
        MongoIterable<Document> iterable=this.mongoDatabase.getCollection("daily_user_actives").aggregate(Arrays.asList(
                Aggregates.match(match),
                Aggregates.group(id,sum("actives","$actives"))
        )).map(
                document -> {
                    Document newDocument=document.get("_id",Document.class);d
                    newDocument.append("actives",document.getLong("actives"));
                    return newDocument;
                }
        );
        List<Document> result=iterable.into(new LinkedList<>());
        return ResponseEntity.ok(result);
    }


----------------------------------------------------------------------------------------------------------------------------------------------------------


    private Bson extractGroupById(String groupBy) {
        Set<String> elements = Sets.newHashSet();
        List<String> splits = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(groupBy);
        elements.addAll(splits);
        List<Bson> filters = Lists.newArrayList();
        if (elements.contains("appid")) {
            filters.add(eq("appid", "$appid"));
        }
        if (elements.contains("date")) {
            filters.add(eq("date", "$date"));
        }
        if (elements.contains("channel")) {
            filters.add(eq("channel", "$channel"));
        }
        if (elements.contains("country")) {
            filters.add(eq("country", "$country"));
        }
        if (elements.contains("adnetwork")) {
            filters.add(eq("adnetwork", "$adnetwork"));
        }
        if (elements.contains("adscene")) {
            filters.add(eq("adscene", "$adscene"));
        }
        if (elements.contains("impressions")) {
            filters.add(eq("impressions", "$impressions"));
        }
        return and(filters);
    }


----------------------------------------------------------------------------------------------------------------------------------------------------------


   private Bson extractMatch(String startDate, String endDate, String appIds) {
        List<Bson> filters = Lists.newArrayList(gte("date", startDate), lte("date", endDate));
        List<App> apps = appService.findAll();
        Set<String> codes = apps.stream().map(App::getCode).collect(Collectors.toSet());
        if (appIds == null) {
            filters.add(in("appid", codes));
            return and(filters);
        }
        Set<String> elements = Sets.newHashSet();
        List<String> splits = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(appIds);
        elements.addAll(splits.stream().filter(codes::contains).collect(Collectors.toSet()));
        filters.add(in("appid", elements));
        return and(filters);
    }


  ps:此部分的配置文件和二是一样的.



原创粉丝点击