引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
# mongodb 配置
data:
mongodb:
host: 192.168.30.129
database: commentdb
单独的创建一个包respository
public interface CommentRepository extends MongoRepository<Comment,String> {
List<Comment> findByArticleid(String ArticleId);
}
编写service
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
//使用原始的api
@Autowired
private MongoTemplate mongoTemplate;
public List<Comment> findAll() {
return commentRepository.findAll();
}
public Comment findById(String commentId) {
// Optional 有效的放置空指针
Optional<Comment> comment = commentRepository.findById(commentId);
if (comment.isPresent()){
return comment.get();
}
return null;
}
public void save(Comment comment) {
commentRepository.save(comment);
}
public void updateById(Comment comment) {
//save 方法主键不存在执行新增,有id,执行修改
commentRepository.save(comment);
}
public void delete(String commentId) {
commentRepository.deleteById(commentId);
}
public List<Comment> findByArticleId(String articleId) {
return commentRepository.findByArticleid(articleId);
}
}
编写controller
@RestController
@RequestMapping("/comment")
public class CommentController {
@Autowired
private CommentService commentService;
@Autowired
private IdWorker idWorker;
// get /comment 查询所有评论
@GetMapping()
public Result findAll(){
List<Comment> list = commentService.findAll();
return new Result(true, StatusCode.OK,"查询成功",list);
}
// get /comment/{commentId}
@GetMapping("{commentId}")
public Result findById(@PathVariable String commentId){
Comment comment= commentService.findById(commentId);
return new Result(true, StatusCode.OK,"查询成功",comment);
}
// post /comment 新增评论
// body
@PostMapping()
public Result save(@RequestBody Comment comment){
//分布式id生成器id
String id = idWorker.nextId()+"";
comment.set_id(id);
comment.setThumbup(0);
comment.setPublishdate(new Date());
commentService.save(comment);
return new Result(true, StatusCode.OK,"新增成功");
}
// put /comment/{commentId}
// body 修改的字段
@PutMapping("{commentId}")
public Result updateById(
@PathVariable String commentId,
@RequestBody Comment comment){
//分布式id生成器id
comment.set_id(commentId);
commentService.updateById(comment);
return new Result(true, StatusCode.OK,"修改成功");
}
// delete /comment/{commentId}
@DeleteMapping("{commentId}")
public Result delete(
@PathVariable String commentId){
commentService.delete(commentId);
return new Result(true, StatusCode.OK,"删除成功");
}
}