引入MongoDB依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置文件进行配置
spring:
data:
mongodb:
host: 127.0.0.1
database: articledb
port: 27017
创建MongoDB实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "comment")
@CompoundIndex(def = "{'userid': 1,'nickname': -1}")
public class Comment implements Serializable {
@Id
private String id;
@Field("content")
private String content;
private Date publishtime;
@Indexed
private String userid;
private String nickname;
private LocalDateTime createdatetime;
private Integer likenum;
private Integer replynum;
private String state;
private String parentid;
private String articleid;
}
创建Dao
public interface CommentRepository extends MongoRepository<Comment,String> {
Page<Comment> findByParentid(String parentid, Pageable pageable);
}
创建service
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
@Autowired
private MongoTemplate mongoTemplate;
public void saveComment(Comment comment){
commentRepository.save(comment);
}
public void updateComment(Comment comment){
commentRepository.save(comment);
}
public void deleteCommentById(String id){
commentRepository.deleteById(id);
}
public List<Comment> findCommentList(){
return commentRepository.findAll();
}
public Comment findCommentById(String id){
return commentRepository.findById(id).get();
}
public Page<Comment> findCommentListByParentif(String parentid,int page,int size){
return commentRepository.findByParentid(parentid, PageRequest.of(page-1,size));
}
public void updateCommentLikenum(String id){
Query query = Query.query(Criteria.where("id").is(id));
Update update = new Update();
update.inc("likenum");
mongoTemplate.updateFirst(query,update,Comment.class);
}
}
创建测试类进行测试
@SpringBootTest
public class CommentServiceTest {
@Autowired
private CommentService commentService;
@Test
public void testSaveComment(){
Comment comment = new Comment("3","test3",new Date(),"1003","刘禅", LocalDateTime.now(),0,0,"okk","1","003");
commentService.saveComment(comment);
}
@Test
public void testFindCommentList(){
System.out.println(commentService.findCommentList());
}
@Test
public void testFindById(){
System.out.println(commentService.findCommentById("1"));
}
@Test
public void testFindCommentListByParentid(){
Page<Comment> page = commentService.findCommentListByParentif("1", 1, 2);
System.out.println(page.getTotalElements());
System.out.println(page.getContent());
}
@Test
public void testUpdateCommentLikenum(){
commentService.updateCommentLikenum("1");
}
}