spring boot 整合mongodb

spring boot 整合spring data mongodb的例子:

项目依赖

pom.xml

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

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
        dependency>
mongodb 配置

application.yaml

spring
  data:
    mongodb:
      host: localhost
      database: test
      port: 27017
实体类

实体类对应于某一个指定的集合
class Student

//指定对应的集合
@Document(collection = "student")
public class Student {
    @Id
    private long id;

    private String name;

    private List hobby;

    private Map grade;
    //get and set 省略了
}    
repository

继承MongoRepository, 就可以获得简单的增删改查的功能了,系统自动帮你实现。同时,还可以按照一定的规则,生成一些自定义的查找方法具体参照 Spring data Mongodb-Query methods

package com.junhua.dao;

import com.junhua.dao.StudentRepositoryCustom;
import com.junhua.pojo.Student;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * Created by xiejunhua on 2017/5/18.
 */
public interface StudentRepository extends MongoRepository<Student, Long> {

    Student findFirstByName(String name);
    //支持json查询 ?0表示第一个参数
    @Query("{'name': ?0}")
    List findUsersByName(String name);
}
自定义操作

要定义些自定义的查询和其他修改操作,需要新建一个接口StudentRepositoryCustom 和接口对应的实现类StudentRepositoryImpl 这里要特别注意实现类的名称,一定要是在StudentRepository 后面加Impl 而不能是其他的
interface StudentRepositoryCustom

package com.junhua.dao;

import java.util.List;

/**
 * Created by xiejunhua on 2017/5/18.
 * Customizing yourself's method to operate collection
 */
public interface StudentRepositoryCustom {

    int updateHobby(String name, List hobbies);
}

class StudentRepositoryImpl

package com.junhua.dao.impl;

import com.junhua.dao.StudentRepositoryCustom;
import com.junhua.pojo.Student;
import com.mongodb.WriteResult;
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 java.util.List;

/**
 * Created by xiejunhua on 2017/5/18.
 * notice the class name must be StudentRepositoryImpl mustn't be StudentRepositoryCustomImpl
 */
public class StudentRepositoryImpl implements StudentRepositoryCustom {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public int updateHobby(String name, List hobbies) {
        Query query = new Query(Criteria.where("name").is(name));

        Update update = new Update().set("hobby", hobbies);

        WriteResult result = mongoTemplate.updateFirst(query, update, Student.class);

        if (result != null) {
            return result.getN();
        } else {
            return 0;
        }
    }
}

class StudentRepository 加上新的继承

package com.junhua.dao;

import com.junhua.pojo.Student;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * Created by xiejunhua on 2017/5/18.
 */
public interface StudentRepository extends MongoRepository<Student, Long>, StudentRepositoryCustom {

    Student findFirstByName(String name);
    @Query("{'name': ?0}")
    List findUsersByName(String name);
}
执行代码

class App

package com.junhua;

import com.junhua.dao.StudentRepository;
import com.junhua.pojo.Student;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiejunhua on 2017/5/17.
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(App.class);
        app.run(args);
    }

    @Bean
    CommandLineRunner init(StudentRepository studentRepository) {

        return new CommandLineRunner() {
            @Override
            public void run(String... strings) throws Exception {

                Student student = new Student();
                ArrayList arrayList = new ArrayList();
                arrayList.add("watch tv");
                arrayList.add("read book");
                Map map = new HashMap();
                map.put("math", 80);
                map.put("English", 70);
                student.setId(1L);
                student.setName("xiaoming");
                student.setHobby(arrayList);
                student.setGrade(map);
                studentRepository.insert(student);
                Student student1 = studentRepository.findFirstByName("xiaoming");
                System.out.println(student1);
                }
            };
        };
    }
}
直接操作,不依赖对象映射和MongoRepository

通过MongoTemplate 来直接执行查询和修改

package com.junhua;

import com.junhua.dao.StudentRepository;
import com.junhua.pojo.Student;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiejunhua on 2017/5/17.
 */
@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(App.class);
        app.run(args);
    }

    @Bean
    CommandLineRunner init(MongoTemplate mongoTemplate) {
        return new CommandLineRunner() {
            @Override
            public void run(String... strings) throws Exception {
                DBCollection dbCollection = mongoTemplate.getCollection("student");
                //拿到这个对象之后,用过Mongodb官方驱动的朋友应该很熟悉 怎么操作了
                BasicDBObject basicDBObject = new BasicDBObject();
                basicDBObject.append("name", "xiaoming");
                DBCursor dbCursor = dbCollection.find(basicDBObject);
                while (dbCursor.hasNext()) {
                    System.out.println(dbCursor.next());
                }
                }
            };
        };
    }
}

项目完整代码 github

你可能感兴趣的:(java,spring-boot,mongodb,spring-boot)