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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值