最近学习MongoDB,看了很多博客和Demo。然后自己用maven搭建了一个SpringBoot集成mongodb的简单Demo。希望大家提出意见,互相学习。
1.首先,安装好mongodb服务
2.新建maven项目。
3.添加SpringBoot和Mongodb依赖。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- springboot-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring-boot-starter-data-mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
4.在application.yml连接本地mongodb。
spring:
data:
mongodb:
uri: mongodb://localhost:27017/test
5.编写User.
public class User {
//id属性是给mongodb用的,用@Id注解修饰
@Id
private Integer id;
private String name;
private int age;
public User(Integer id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
6.编写User的Repository.
public interface UserRepository extends MongoRepository<User, String> {
User findByName(String name);
}
7.编写User的UserService接口和实现.
@Repository
public interface UserService {
void save(User user);
User findByName(String name);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
public void save(User user) {
userRepository.save(user);
}
public User findByName(String name) {
return this.userRepository.findByName(name);
}
}
8.编写Controller
@RestController
public class Controller {
@Autowired
private UserService userService;
@Autowired
private MongoTemplate mongoTemplate;
/**
* save use before findName
* @return
*/
@GetMapping("/save")
public User save() {
User user = new User(2, "Tseng", 21);
mongoTemplate.save(user);
//也可以使用Repository插入数据,userService.save(user);
return user;
}
@GetMapping("/find")
public List<User> find() {
List<User> userList = mongoTemplate.findAll(User.class);
return userList;
}
/**
* input String name "Tseng"
* @param name
* @return
*/
@GetMapping("/findByName")
public User findByName(@RequestParam("name") String name) {
User user = userService.findByName(name); return user; }}9,mongodb查询插入数据
10.条件查询:http://localhost:8080/findByName?name=Tseng
Demo已经发布到Github上,地址:https://github.com/WunHwanTseng/github