您的位置:首页 > 数据库 > Mongodb

spring boot 整合mongodb

2017-05-18 17:15 573 查看
spring boot 整合spring data mongodb的例子:

项目依赖

pom.xml

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</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<Student> 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 St
4000
udentRepositoryCustomImpl
*/
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<Student> 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<String, Integer>();
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mongodb spring-boot