mongodb+springboot操作

pom.xml加入依赖

<parent>
		<groupId>org.springframework.bootgroupId>
		<artifactId>spring-boot-starter-parentartifactId>
		<version>2.1.0.RELEASEversion>
		<relativePath/> 
	parent>

	<properties>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
		<java.version>1.8java.version>
	properties>

 <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <fork>truefork>
                configuration>
            plugin>
        plugins>
    build>

配置文件

spring.data.mongodb.uri= mongodb://xxx:27017/data_dict
默认端口27017

建类


import java.io.Serializable;

import org.springframework.data.annotation.Id;

/** 
* 
*  
* @author luansjr
* @date 2018年11月13日 下午3:24:37
* 
*/

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+"\"}\"";
    }
}

UserRepository


import java.util.List;

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;

/**
 * Created by nbfujx on 2017-12-08.
 */
public interface UserRepository extends MongoRepository<User, Long> {
	@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);
    /**
     * 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)

    

}

测试

mongodb插入100w数据测试

  @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTest {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserRepository userRepository;

    @Before
    public void setUp() {
        //userRepository.deleteAll();
    }

//    @Test
    public void test() throws Exception {

        // 创建10个User,并验证User总数
        userRepository.save(new User(1L, "didi", 30));
        userRepository.save(new User(2L, "mama", 40));
        userRepository.save(new User(3L, "kaka", 50));
        userRepository.save(new User(4L, "didi2", 30));
        userRepository.save(new User(5L, "mama", 40));
        userRepository.save(new User(6L, "kaka2", 50));
        userRepository.save(new User(7L, "kaka", 50));
        userRepository.save(new User(8L, "kao", 50));
        userRepository.save(new User(9L, "ekakae", 50));
        userRepository.save(new User(10L, "kaka5", 50));
        userRepository.save(new User(11L, "", 50));
        userRepository.save(new User(12L, null, 50));
        this.logger.info(String.valueOf(userRepository.findAll().size()));

        // 删除一个User,再验证User总数
        /*User u = userRepository.findOne(1L);
        this.logger.info(u.toString());
        userRepository.delete(u);
        this.logger.info(String.valueOf(userRepository.findAll().size()));

        // 删除一个User,再验证User总数
        u = userRepository.findByUsername("mama").get(0);
        this.logger.info(u.toString());
        userRepository.delete(u);
        this.logger.info(String.valueOf(userRepository.findAll().size()));*/

    }

//    @Test
    public void test2() throws Exception {

        // 删除一个User,再验证User总数
        List<User> u1 = userRepository.findByUsernameLike("kaka");
        this.logger.info(u1.toString());
        List<User> u2 = userRepository.findByUsername("mama");
        this.logger.info(u2.toString());
        List<User> u3 = userRepository.findByAgeGreaterThan(40);
        this.logger.info(u3.toString());
        List<User> u4 = userRepository.findByAgeLessThan(40);
        this.logger.info(u4.toString());
        List<User> u5 = userRepository.findByAgeBetween(30,45);
        this.logger.info(u5.toString());
        List<User> u6 = userRepository.findByUsernameNotNull();
        this.logger.info(u6.toString());
        List<User> u7 = userRepository.findByUsernameNull();
        this.logger.info(u7.toString());
        List<User> u8 = userRepository.findByUsernameNot("kaka");
        this.logger.info(u8.toString());




    }

//    @Test
    public void test3() throws Exception {

        Pageable pageable = new PageRequest(0,10);
        Page<User> u1 = userRepository.findByNameAndAgeRange("kaka",50,pageable);
        this.logger.info(u1.toString());
        Page<User> u2 = userRepository.findByNameAndAgeRange2("kaka",0,50,pageable);
        this.logger.info(u2.toString());
        Page<User> u3 = userRepository.findByNameAndAgeRange3("kaka",0,50,pageable);
        this.logger.info(u3.toString());

    }
//    @Test
    public void test4() throws Exception {
    	List<User> userList=new ArrayList<User>();
    	List<User> userListOld=userRepository.findAll();
    	Date now=new Date();
    	Long start=now.getTime();
    	Long userId=userListOld.get(userListOld.size()-1).getId();
    	for(int i=0;i<100;i++){
    		userList=new ArrayList<User>();
    		for(int j=0;j<10000;j++){
    			
    			userList.add(new User(userId+i*j+10L, "user"+i*j, 50+i*j));
    		}
    		userRepository.saveAll(userList);
    	}
    	
        Pageable pageable = new PageRequest(0,10);
        now=new Date();
        Long end=now.getTime();
        List<User>  u3 = userRepository.findAll();
        this.logger.info(u3.size()+"");
        Long interval=(end-start)/(1000*60);
        this.logger.info(interval.toString());
    }
    
    @Test
    public void test5() throws Exception {
    	List<User> userList=new ArrayList<User>();
    	List<User> userListOld=userRepository.findAll();
    	
        this.logger.info(userListOld.size()+"");
        this.logger.info(userListOld.toString());
    }
    
}

你可能感兴趣的:(JAVA,数据库,mongodb)