1. 程式人生 > >Spring Boot中引入MongoDB

Spring Boot中引入MongoDB

Spring JDBC提供模板類簡化對資料庫的操作,本文使用MongoTemplate類,當然也可以用Repository介面。
僅模擬實現查詢,其他建庫、插入資料等操作見【Linux下MongoDB安裝配置

1、MongoDB配置

pom.xml

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

application.properties

spring.data.mongodb.uri=mongodb://admin:123456@localhost:27017/mymongo

2、業務模擬

MongoDB實體

package com.test.demo.mongo;

import java.io.Serializable;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
//文件儲存在集合中,故指定集合 //If not configured, a default collection name will be derived from the type's name. @Document(collection = "mycol") public class UserEntity implements Serializable { private static final long serialVersionUID = 1L; @Field("_id") private String id; private String name; private int age;
get,set。。。 }

dao介面

package com.test.demo.mongo;

public interface UserDao {
	public UserEntity findByUsername(String userName);
}

dao實現類
Criteria is Central class for creating queries. It follows a fluent API style so that you can easily chain together multiple criteria. Static import of the Criteria.where method will improve readability.
MongoDB Query object representing criteria, projection, sorting and query hints.

package com.test.demo.mongo;

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.stereotype.Component;

@Component
public class UserDaoImpl implements UserDao{
	@Autowired
    private MongoTemplate mongoTemplate;

	@Override
	public UserEntity findByUsername(String username) {
		Query query=new Query(Criteria.where("name").is(username));
        return  mongoTemplate.findOne(query , UserEntity.class);
	}

}

Controller類
在HelloController類中,新增如下內容:

	@Resource
	UserDao mongoService;
	
	@RequestMapping("/getMongoUser")
	public UserEntity getMongoUser(UserInfo key) {
		return this.mongoService.findByUsername(key.getUsername());
	}

3、執行

瀏覽器中訪問http://cos6743:8081/getMongoUser?username=tom
返回結果:{"_id":“5c27003cc34d39cfce99bc35”,“name”:“tom”,“age”:35}
tom