Spring Boot——使用MongoDB
2018-09-28 本文已影响11人
莫问以
什么是MongoDB?MongoDB是文档型的NoSQL数据库,具有大数据量、高并发等优势,但缺点是不能建立实体关系,而且也没有事务管理机制。下面我们就看一下在Spring Boot基础下,如何使用MongoDB,编写数据访问。
引入Starer:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
确认装有MongoDB以后,新建application.yml配置mongodb:
#配置mongodb参数
spring:
data:
mongodb:
host: 172.30.0.218
port: 27017
database: mydb
#配置server参数
server:
port: 9000
新建Entity:
package com.guxf.demo.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "user")
public class User {
@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;
}
//getter和setter方法略
}
package com.guxf.demo.service;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.guxf.demo.entity.User;
@Repository
@Service
public interface UserService {
void save(User user);
User findByName(String name);
}
package com.guxf.demo.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.guxf.demo.entity.User;
public interface UserRepository extends MongoRepository<User, String> {
User findByName(String name);
}
package com.guxf.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.guxf.demo.entity.User;
import com.guxf.demo.service.UserService;
@RestController
@RequestMapping(value="/com/guxf/demo/entity/User")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private MongoTemplate mongoTemplate;
@GetMapping("/save")
public User save() {
User user = new User(2, "Tseng", 21);
mongoTemplate.save(user);
return user;
}
@GetMapping("/find")
public List<User> find() {
List<User> userList = mongoTemplate.findAll(User.class);
return userList;
}
@GetMapping("/findByName")
public User findByName(@RequestParam("name") String name) {
User user = userService.findByName(name);
return user;
}
}
启动Application,浏览器输入:http://localhost:9000/save