springboot04-mongodb

1.搭建mongodb服务

在https://www.mongodb.com/下载mongodb安装包,解压到本地

cmd中执行命令,启动本地mongodb:

  cd D:\Program Files\mongodb-win32-x86_64-3.2.0\bin

  mongod.exe --dbpath D:\mongodata\db --logpath D:\mongodata\log\mongodb.log

使用可视化管理软件mongoChef查看本地mongodb数据库

 

2.springboot项目的maven依赖中添加 spring-boot-starter-data-mongodb支持:

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

3.application.properties中添加mongodb地址:

spring.data.mongodb.uri=mongodb://localhost:27017/test

4.新建实体bean类User:

package com.mlxs.springboot04.mongodb.bean;


import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.Date;

/**
 * User类描述:
 *
 * @author yangzhenlong
 * @since 2017/2/14
 */
@Document(collection = "user")
public class User {
    @Id
    private String id;
    private String name;
    private int sex = 0;//0 男,1 女
    private String phone;
    private Date createTime;

    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 int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

 5.数据库操作类:

public interface UserDao extends MongoRepository<User, String> {

    User findByName(String name);//根据name查询

    User findByNameAndPhone(String name, String phone);

    List<User> findAllBySexOrderByCreateTimeDesc(Integer sex);//根据性别查询,并根据创建时间倒序

}

附加mongodb keywords 地址:

http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#repository-query-keywords

可以查找一下spring data jpa-mongo 的命名规范,如:

 

6.单元测试类:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mlxs.springboot04.mongodb.bean.User;
import com.mlxs.springboot04.mongodb.dao.UserDao;
import com.mlxs.springboot04.mongodb.web.MainApp;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Date;
import java.util.List;

/**
 * UserDaoTest类描述:
 *
 * @author yangzhenlong
 * @since 2017/2/14
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(MainApp.class)
public class UserDaoTest {
    @Autowired
    private UserDao userDao;

    @Autowired
    private ObjectMapper objectMapper;

    @Test
    public void testAll() throws JsonProcessingException {
        this.add();
        this.delete();
        this.findByName();
        this.findByNameAndPhone();
        this.findAllBySexOrderByCreateTimeDesc();
    }

    @Test
    public void add() throws JsonProcessingException {
        System.out.println("--------------添加-------------");
        for(int i = 1; i <= 10; i++) {
            User user = new User();
            user.setName("测试" + i);
            user.setSex((i%2 == 0) ? 0 : 1);
            user.setPhone("1511111000" + i);
            user.setCreateTime(new Date());
            User save = userDao.save(user);
            System.out.println("保存结果:" + objectMapper.writeValueAsString(save));
        }
    }

    @Test
    public void delete() throws JsonProcessingException {
        System.out.println("--------------删除-------------");
        User user = userDao.findByName("测试6");
        userDao.delete(user);
        List<User> users = userDao.findAll();
        System.out.println("删除后的列表:" + objectMapper.writeValueAsString(users));
    }

    @Test
    public void findByName() throws JsonProcessingException {
        System.out.println("--------------findByName-------------");
        User user = userDao.findByName("测试1");
        System.out.println("findByName:" + objectMapper.writeValueAsString(user));
    }

    @Test
    public void findByNameAndPhone() throws JsonProcessingException {
        System.out.println("--------------findByNameAndPhone-------------");
        User user = userDao.findByNameAndPhone("测试1", "15111110001");
        System.out.println("findByNameAndPhone:" + objectMapper.writeValueAsString(user));
    }

    @Test
    public void findAllBySexOrderByCreateTimeDesc() throws JsonProcessingException {
        System.out.println("--------------findAllBySexByCreateTimeDesc-------------");
        List<User> userList = userDao.findAllBySexOrderByCreateTimeDesc(1);
        System.out.println("findAllBySexOrderByCreateTimeDesc:" + objectMapper.writeValueAsString(userList));
    }
}

 

#注意#:如果报Could not autowire field userRepository 类似的错误,则说明不能正确注入mongoRepository的子类,需要在springboot启动类中添加如下注解:

@SpringBootApplication
@EnableMongoRepositories(basePackages = {"com.mlxs.springboot04.mongodb.dao"})
public class MainApp {

    public static void main(String[] args) {

        SpringApplication.run(MainApp.class, args);
    }
}

 

测试结果:

 

posted @ 2017-02-15 11:05  艺言弈行  阅读(884)  评论(0编辑  收藏  举报