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}