1.首先,安装好mongodb服务
2.新建maven项目。
3.添加SpringBoot和Mongodb依赖。
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 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 classController{
@Autowired
privateUserService userService;
@Autowired
privateMongoTemplate mongoTemplate;
/**
* save use before findName
* @return
*/
@GetMapping("/save")
publicUser save() {
User user=newUser(2,"Tseng",21);
mongoTemplate.save(user);
//也可以使用Repository插入数据,userService.save(user);
return user;
}
@GetMapping("/find")
publicListfind() {
List userList=mongoTemplate.findAll(User.class);
return userList;
}
/**
* input String name "Tseng"
* @paramname
* @return
*/
@GetMapping("/findByName")
public User findByName(@RequestParam("name") String name) {
User user = userService.findByName(name); return user; }}9,mongodb查询插入数据