springboot整合mongodb
1.代码实现:
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
控制层
@RestController
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/findAll")
public List<User> findAll(){
return userService.findAll();
}
@GetMapping("/findByName")
public User findByName(String name){
return userService.findByName(name);
}
@PostMapping("/add")
public String add(User user){
return userService.add(user);
}
@PutMapping("/edit")
public String edit(User user){
return userService.edit(user);
}
@DeleteMapping("/deleteById")
public String deleteById(Long id){
return userService.deleteById(id);
}
}
接口层
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserRepository userRepository;
@Override
public List<User> findAll() {
return userRepository.findAll();
}
@Override
public User findByName(String name) {
return userRepository.findByName(name);
}
@Override
public String add(User user) {
userRepository.save(user);
return "添加成功";
}
@Override
public String edit(User user) {
userRepository.save(user);
return "修改成功";
}
@Override
public String deleteById(Long id) {
userRepository.deleteById(id);
return "删除成功";
}
}
访问层
public interface UserRepository extends MongoRepository<User, Long> {
User findByName(String name);
}
实体类
@Data
public class User {
@Id
private Long id;
private String name;
private Integer age;
}
2.效果实现:
运行项目,打开postman发起请求添加数据
查询数据