1:build.gradle 添加mongodb依赖
dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-data-mongodb') compile group: 'org.mongodb', name: 'mongo-java-driver', version: '3.4.2' testCompile('org.springframework.boot:spring-boot-starter-test')}
2:启动本地mongdb服务
D:\MongoDB\Server\3.4\bin>mongod --config "D:\MongoDB\Server\3.4\mongo.conf" --auth
3:配置application.properties文件
#mongodb configspring.data.mongodb.host=127.0.0.1spring.data.mongodb.port=27017spring.data.mongodb.username=gwzhspring.data.mongodb.password=gwzhspring.data.mongodb.database=gwzhspring.data.mongodb.authentication-database=gwzh#server configserver.port=9001
4:代码
(1)UserVo.java
package com.example.user;import org.springframework.data.annotation.Id;/** * Created by yan on 2017/4/25. */public class UserVo { @Id private String userid; private String username; private Integer age; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } 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; }}
(2)UserRepository.java
package com.example.user;import org.springframework.data.mongodb.repository.MongoRepository;/** * Created by yan on 2017/4/25. */public interface UserRepository extends MongoRepository{ UserVo findByUserid(String userid);}
(3)UserCtrl.java
package com.example.user;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.List;/** * Created by yan on 2017/4/25. */@RestController@RequestMapping( value = "/user", produces = "application/json;charset=utf-8", headers = "Accept=application/json")public class UserCtrl { @Autowired UserRepository userRepository; @RequestMapping( value = "/add", method = RequestMethod.POST ) public UserVo addUser(@RequestBody UserVo vo){ return userRepository.save(vo); } @RequestMapping( value = "/list", method = RequestMethod.GET ) public ListgetUsers(){ return userRepository.findAll(); } @RequestMapping( value = "/delete", method = RequestMethod.POST ) public boolean deleteUser(@RequestBody UserVo vo){ userRepository.delete(vo.getUserid()); return true; }}
5:测试