准备MongoDB环境
参见其他文章
新建SPring boot application
使用spring initializer,新建spring boot application,引入相关依赖为
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
在 SpringBoot 的 application.yml 文件中添加连接 MongoDB 的配置参数,内容如下:
server:
port: 7070
spring:
data:
mongodb:
host: 127.0.0.1
port: 27017
authentication-database: admin
database: test
username: admin
password: admin
参数介绍:
- spring.data.mongodb.host: 指定 MongoDB Server 地址
- spring.data.mongodb.port: 指定 MongoDB Server 端口
- spring.data.mongodb.database: 指定使用的数据库
- spring.data.mongodb.username: MongoDB 用户名
- spring.data.mongodb.password: MongoDB 密码
编写代码
- Controller layer
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: UserController.java
* @Prject: mongospringboot
* @Package: com.springboot.mongo.controller
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.springboot.mongo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.mongo.entity.User;
import com.springboot.mongo.service.UserService;
/**
* @ClassName: UserController
* @Description: TODO
* @author: Jay
* @date: 2021-10-15
*/
@RestController
@RequestMapping("/Mongo")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/get/{id}")
public User getByUserId(@PathVariable("id") Integer id) {
return userService.getByUserId(id);
}
@PostMapping("/post")
public User addNewUser(@RequestBody User user) {
return userService.addNewUser(user);
}
}
- Service layer
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: UserService.java
* @Prject: mongospringboot
* @Package: com.springboot.mongo.service
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.springboot.mongo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.mongo.dao.UserRepository;
import com.springboot.mongo.entity.User;
/**
* @ClassName: UserService
* @Description: TODO
* @author: Jay
* @date: 2021-10-15
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
/**
* @Title: getByUserId
* @Description: TODO
* @param id
* @return
* @return: User
*/
public User getByUserId(Integer id) {
// TODO Auto-generated method stub
return userRepository.findById(id).get();
}
/**
* @Title: addNewUser
* @Description: TODO
* @param user
* @return
* @return: User
*/
public User addNewUser(User user) {
// TODO Auto-generated method stub
return userRepository.insert(user);
}
}
- DAO layer
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: UserRepository.java
* @Prject: mongospringboot
* @Package: com.springboot.mongo.dao
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.springboot.mongo.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.springboot.mongo.entity.User;
/**
* @ClassName: UserRepository
* @Description: TODO
* @author: Jay
* @date: 2021-10-15
*/
@Repository
public interface UserRepository extends MongoRepository<User, Integer> {
}
- Entity layer
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: User.java
* @Prject: mongospringboot
* @Package: com.springboot.mongo.entity
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.springboot.mongo.entity;
import org.springframework.data.mongodb.core.mapping.MongoId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @ClassName: User
* @Description: TODO
* @author: Jay
* @date: 2021-10-14
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
@MongoId
private Integer userID;
private String firstName;
private String lastName;
private String gender;
private Integer age;
}
测试
- 插入数据
{
"userID": 1,
"firstName": "Michael",
"lastName": "Lan",
"gender": "M",
"age": 18
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lKxRZ6tK-1666898278470)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/33969fbf34bf4c2ebf5ba28c49636357~tplv-k3u1fbpfcp-watermark.image?)]
去MongoDB中查询结果
> show dbs;
admin 0.000GB
config 0.000GB
customers 0.000GB
local 0.000GB
test 0.000GB
> use test
switched to db test
> show collections
user
> db.user.find().pretty()
{
"_id" : 1,
"firstName" : "Michael",
"lastName" : "Lan",
"gender" : "M",
"age" : 18,
"_class" : "com.springboot.mongo.entity.User"
}
>
- 查询数据
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0SIIXll1-1666898278471)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/6db2758167f14be8b1e1200284b9485f~tplv-k3u1fbpfcp-watermark.image?)]
不使用DAO layer(Repository),在Service layer注入MongoTemplate,操作数据。
新建一个Service
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: UserTmService.java
* @Prject: mongospringboot
* @Package: com.springboot.mongo.service
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.springboot.mongo.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import com.springboot.mongo.entity.User;
/**
* @ClassName: UserTmService
* @Description: TODO
* @author: Jay
* @date: 2021-10-15
*/
@Service
public class UserTmService {
@Autowired
private MongoTemplate mongoTemplate;
public User getByUserId(Integer Id) {
return mongoTemplate.findById(Id, User.class);
}
public List<User> getAllUser() {
return mongoTemplate.findAll(User.class);
}
public User addNewUser(User user) {
return mongoTemplate.insert(user);
}
public void deleteById(Integer Id) {
Query query = new Query();
query.addCriteria(Criteria.where("userID").is(Id));
mongoTemplate.remove(query, User.class);
}
}
新建一个Controller
/**
* Copyright: 2021 Hswfit. All rights reserved.
*
* @Title: UserTmController.java
* @Prject: mongospringboot
* @Package: com.springboot.mongo.controller
* @Description: TODO
* @author: Jay
* @version: V1.0
*/
package com.springboot.mongo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.mongo.entity.User;
import com.springboot.mongo.service.UserTmService;
/**
* @ClassName: UserTmController
* @Description: TODO
* @author: Jay
* @date: 2021-10-15
*/
@RestController
@RequestMapping("/MongoTm")
public class UserTmController {
@Autowired
private UserTmService userTmService;
@GetMapping("/list")
public List<User> getAllUser() {
return userTmService.getAllUser();
}
@GetMapping("/get/{Id}")
public User getByUserId(@PathVariable("Id") Integer Id) {
return userTmService.getByUserId(Id);
}
@PostMapping("/post")
public User AddNewUser(@RequestBody User user) {
return userTmService.addNewUser(user);
}
@DeleteMapping("/delete/{Id}")
public void DeleteUser(@PathVariable("Id") Integer Id) {
userTmService.deleteById(Id);
}
}
测试结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vi79rHWp-1666898278472)(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/d377f04111904376a2308d1dc9b09ddf~tplv-k3u1fbpfcp-watermark.image?)]