spring boot 集成mongo配置

一、首先在pom文件中加入如下依赖


	 
	    org.springframework.boot
	    spring-boot-starter-data-mongodb
	 

二、在application.properties配置文件中加入 spring.data.mongodb.uri配置连接MongoDB数据库,可以在单个数据库或者多副本集集数据库集群的时候使用如下配置:

spring.data.mongodb.uri=mongodb://user:[email protected]:12345,mongo2.example.com:23456/test

三、配置数据库实体类

package ggauthority.v1.user.entity;

import java.io.Serializable;

import org.springframework.stereotype.Component;

@Component
public class User implements Serializable{


	/**
	 * 
	 */
	private static final long serialVersionUID = -1729604149803368916L;
	private Long id;
	private String userName;
	private String password;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

四、配置数据库持久层

package ggauthority.v1.user.UserDaoImpl;

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 org.springframework.stereotype.Repository;

import ggauthority.v1.user.entity.User;
import ggauthority.v1.user.userDao.UserDao;

@Repository
public class UserDaoImpl implements UserDao{

	@Autowired
    private MongoTemplate mongoTemplate;
	
	@Override
	public void saveUser(User user) {
		this.mongoTemplate.save(user);
		
	}

	@Override
	public User findUserByUserName(String userName) {
		Query query=new Query(Criteria.where("userName").is(userName));
        User user =  this.mongoTemplate.findOne(query , User.class);
        return user;
	}

	@Override
	public void updateUser(User user) {
		Query query=new Query(Criteria.where("id").is(user.getId()));
        Update update= new Update().set("userName", user.getUserName()).set("password", user.getPassword());
        //更新查询返回结果集的第一条
        this.mongoTemplate.updateFirst(query,update,User.class);
		
	}

	@Override
	public void deleteUserById(Long id) {
		Query query=new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,User.class);
		
	}

}

五、中间的service层和dao接口及控制器类自己开发,按照如上写法成功了!!!!!!

你可能感兴趣的:(【spring,MVC】)