目录
- 引入MongoDB依赖
- 配置文件进行配置
- 创建MongoDB实体类
- 创建Dao
- 创建service
- 创建测试类进行测试
引入MongoDB依赖
org.springframework.boot
spring-boot-starter-data-mongodb
配置文件进行配置
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
//继承MongoRepository类,
public interface CommentRepository extends MongoRepository {
//分页查询,会自动解析,只能叫findByParentid才会解析
Page findByParentid(String parentid, Pageable pageable);
}
创建service
@Service
public class CommentService {
//有两种方式操作MongoDB,一种是spring data mongodb,另外一种是mongotemplate
@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 findCommentList(){
return commentRepository.findAll();
}
public Comment findCommentById(String id){
return commentRepository.findById(id).get();
}
public Page 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("1","test1",new Date(),"1001","貂蝉", LocalDateTime.now(),0,0,"okk",null,"001");
// Comment comment = new Comment("2","test2",new Date(),"1002","吕布", LocalDateTime.now(),0,0,"okk",null,"002");
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 page = commentService.findCommentListByParentif("1", 1, 2);
System.out.println(page.getTotalElements());
System.out.println(page.getContent());
}
@Test
public void testUpdateCommentLikenum(){
commentService.updateCommentLikenum("1");
}
}