springboot干货——(十四【一】)整合mongodb

mongodb这块我就不介绍了,不了解的小伙伴可以移步mongodb教程

直接上项目

1.项目结构图如下:

springboot干货——(十四【一】)整合mongodb_第1张图片


2.pom.xml如下



	4.0.0

	com.gwd
	springboot-mongodb
	0.0.1-SNAPSHOT
	jar

	springboot-mongodb
	Demo project for springboot-mongodb

	
		org.springframework.boot
		spring-boot-starter-parent
		1.5.10.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

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

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
		
			org.springframework.boot
			spring-boot-starter-web
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

3.application.properties

有密码的如下:

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test

name对应用户名,pass对应密码

没有密码的如下:

spring.data.mongodb.uri=mongodb://localhost:27017/test

4.model层

User:

public class User {
	@Id
    private Long id;

    private String username;
    private Integer age;
    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 Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public User(Long id, String username, Integer age) {
        this.id = id;
        this.username = username;
        this.age = age;
    }
}

5.Repository

UserRepository:

public interface UserRepository extends MongoRepository{
	
	User findByUsername(String username);
}


6.Controller
package com.gwd.controller;
/** 
* @FileName TestController.java
* @Description:TODO
* @author JackHisen(gu.weidong)
* @version V1.0
* @createtime 2018年2月23日 下午5:02:05 
* 修改历史:
* 时间           作者          版本        描述
*====================================================  
*
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gwd.model.User;
import com.gwd.repository.UserRepository;

@RestController
public class TestController {
	@Autowired
	private UserRepository userRepository;
	
	@RequestMapping("/testMongodb")
	public String testMongodb() {
		// 创建三个User,并验证User总数
		userRepository.save(new User(1L, "didi", 30));
		userRepository.save(new User(2L, "mama", 40));
		userRepository.save(new User(3L, "kaka", 50));
		System.out.println(userRepository.findAll().size());

		// 删除一个User,再验证User总数
		User u = userRepository.findOne(1L);
		userRepository.delete(u);
		System.out.println(userRepository.findAll().size());

		// 删除一个User,再验证User总数
		u = userRepository.findByUsername("mama");
		userRepository.delete(u);
		System.out.println(userRepository.findAll().size());
		return userRepository.findByUsername("kaka").getUsername();
	}
}

7.测试

springboot干货——(十四【一】)整合mongodb_第2张图片

springboot干货——(十四【一】)整合mongodb_第3张图片

你可能感兴趣的:(Spring,Boot,Springboot干货系列)