当前位置:Gxlcms > 数据库问题 > springBoot整合MongoDB(单机)

springBoot整合MongoDB(单机)

时间:2021-07-01 10:21:17 帮助过:14人阅读

mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>

 

配置

application.properties:

#spring.data.mongodb.uri=mongodb://localhost:27017/sea
spring.data.mongodb.uri=mongodb://用户名:密码@localhost:27017/sea

 

 

方式:1: 使用 

@Autowired
private MongoTemplate mongoTemplate;

eg:

技术分享图片
package com.icil.dao;

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.Repository;

import com.icil.domain.UserEntity;
@Repository
public class UserDAO {
    
    
    
      @Autowired
        private MongoTemplate mongoTemplate;

        /**
         * 创建对象
         * @param user
         */
        public void saveUser(UserEntity user) {
            mongoTemplate.save(user);
        }

        /**
         * 根据用户名查询对象
         * @param userName
         * @return
         */
        public UserEntity findUserByUserName(String userName) {
            Query query=new Query(Criteria.where("userName").is(userName));
            UserEntity user =  mongoTemplate.findOne(query , UserEntity.class);
            return user;
        }

        /**
         * 更新对象
         * @param user
         */
        public void updateUser(UserEntity user) {
            Query query=new Query(Criteria.where("id").is(user.getId()));
            Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
            //更新查询返回结果集的第一条
            mongoTemplate.updateFirst(query,update,UserEntity.class);
            //更新查询返回结果集的所有
            // mongoTemplate.updateMulti(query,update,UserEntity.class);
        }

        /**
         * 删除对象
         * @param id
         */
        public void deleteUserById(Long id) {
            Query query=new Query(Criteria.where("id").is(id));
            mongoTemplate.remove(query,UserEntity.class);
        }

}
View Code

 

方式2:extends MongoRepository

eg:

UserRepository.java

技术分享图片
package com.goku.demo.repository;

import com.goku.demo.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

import java.util.List;

/**
 * Created by nbfujx on 2017-12-08.
 */
public interface UserRepository extends MongoRepository<User, Long> {

    /**
     * Like(模糊查询)
     * {"username" : name} ( name as regex)
     * */
    List<User> findByUsernameLike(String username);

    /**
     * Like(模糊查询)
     * {"username" : name}
     * */
    List<User> findByUsername(String username);

    /**
     * GreaterThan(大于)
     * {"age" : {"$gt" : age}}
     * */
    List<User> findByAgeGreaterThan(int age);
    /**
     * LessThan(小于)
     * {"age" : {"$lt" : age}}
     * */
    List<User> findByAgeLessThan(int age);
    /**
     * Between(在...之间)
     * {{"age" : {"$gt" : from, "$lt" : to}}
     * */
    List<User> findByAgeBetween(int from, int to);

    /**
     * IsNotNull, NotNull(是否非空)
     *  {"username" : {"$ne" : null}}
     * */
    List<User> findByUsernameNotNull();

    /**
     * IsNull, Null(是否为空)
     *   {"username" : null}
     * */
    List<User> findByUsernameNull();


    /**
     * Not(不包含)
     *    {"username" : {"$ne" : name}}
     * */
    List<User> findByUsernameNot(String name);



    /**
     *  Near(查询地理位置相近的)
     *  {"location" : {"$near" : [x,y]}}
     * */
     // findByLocationNear(Point point)


    /**
     * Within(在地理位置范围内的)
     *   {"location" : {"$within" : {"$center" : [ [x, y], distance]}}}
     * */
    //findByLocationWithin(Circle circle)


    /**
     *   Within(在地理位置范围内的)
     *     {"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}
     * */
   // findByLocationWithin(Box box)


    @Query("{\"username\":{\"$regex\":?0}, \"age\": ?1}")
    Page<User> findByNameAndAgeRange(String name,int age,Pageable page);

    @Query(value="{\"username\":{\"$regex\":?0},\"age\":{\"$gte\":?1,\"$lte\": ?2}}")
    Page<User> findByNameAndAgeRange2(String name,int ageFrom,int ageTo,Pageable page);

    @Query(value="{\"username\":{\"$regex\":?0},\"age\":{\"$gte\":?1,\"$lte\": ?2}}",fields="{\"username\" : 1, \"age\" : 1}")
    Page<User> findByNameAndAgeRange3(String name,int ageFrom,int ageTo,Pageable page);

}
View Code

 

User:

技术分享图片
package com.goku.demo.model;

import org.springframework.data.annotation.Id;

import java.io.Serializable;


public class User implements Serializable {

    private static final long serialVersionUID = -1L;

    @Id
    private Long id;
    private String username;
    private Integer age;

    public User(Long id, String username, Integer age) {
        this.id = id;
        this.username = username;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "\"User:{\"id\":\""+id+"\",\"username\":\""+username+"\",\"age\":\""+age+"\"}\"";
    }
}
View Code

 

springBoot整合MongoDB(单机)

标签:单机   http   rom   code   delete   static   用户名   mongo   Pageable   

人气教程排行