01 引言
本文的代码已上传至Github,有兴趣的同学可以Clone下来看看https://github.com/ylw-github/SpringBoot-Mongo-Demo.git
讲解本文前,先熟悉MongoDB中常用的几种数据类型:
数据类型描述Object ID文档IDString字符串,最常用,必须是有效的UTF-8Boolean存储一个布尔值,true或falseInteger整数可以是32位或64位,这取决于服务器Double存储浮点值Arrays数组或列表,多个值存储到一个键Object用于嵌入式的文档,即一个值为一个文档Null存储Null值Timestamp时间戳Date存储当前日期或时间的UNIX时间格式本文主要讲解在SpringBoot下整合MongoDB,实现文章评论的“增”、“删”、“改”、“查”
功能,其中文章评论MongoDB的表结构设计如下:
本文目录结构如下: l____ 01 引言 l____ 02 环境搭建 l____ 03 配置 l____ 04 编码实现 l____ 05 单元测试
02 环境搭建① 首先在Linux下搭建MongoDB服务,可参考之前写过的一篇文章《Linux下安装MongoDB》
② 新建一个SpringBoot-Mongo-Demo的maven项目:
① 添加maven依赖,如下:
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-data-mongodb
② 配置application.yml,配置内容如下:
spring:
#数据源配置
data:
mongodb:
# 主机地址
host: 192.168.162.137
# 数据库
database: articledb
# 默认端口是27017
port: 27017
#也可以使用uri连接
#uri: mongodb://bobo:123456@180.76.159.126:27017,180.76.159.126:27018,180.76.159.126:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs
③ 配置启动类:
@SpringBootApplication
public class ArticleApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleApplication.class, args);
}
}
04 编码实现
① 定义实体类Comment
/**
* 文章评论实体类
*
* ① @Document 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
*
*
*
* description:
* - Document 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
* - 格式:@Document(collection="mongodb 对应 collection 名")
*
* create by: YangLinWei
* create time: 2020/7/15 3:28 下午
*/
//若未加 @Document ,该 bean save 到 mongo 的 comment collection
//若添加 @Document ,则 save 到 comment collection
@Document(collection="comment")//可以省略,如果省略,则默认使用类名小写映射集合
//复合索引
@CompoundIndex( def = "{'userid': 1, 'nickname': -1}")
public class Comment implements Serializable {
//主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫“id”,则该注解可以省略,否则必须写
// @Id
private String id;//主键
//该属性对应mongodb的字段的名字,如果一致,则无需该注解
@Field("content")
private String content;//吐槽内容
private Date publishtime;//发布日期
//添加了一个单字段的索引
@Indexed
private String userid;//发布人ID
private String nickname;//昵称
private LocalDateTime createdatetime;//评论的日期时间
private Integer likenum;//点赞数
private Integer replynum;//回复数
private String state;//状态
private String parentid;//上级ID
private String articleid;
//getter and setter.....
}
② 定义CommentRepository数据库:
public interface CommentRepository extends MongoRepository {
Page findByParentid(String parentid, Pageable pageable);
}
③定义Service类:
@Service
public class CommentService {
@Autowired
private CommentRepository commentRepository;
@Autowired
private MongoTemplate mongoTemplate;
/**
* 保存一个评论
* @param comment
*/
public void saveComment(Comment comment){
//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键
//设置一些默认初始值。。。
//调用dao
commentRepository.save(comment);
}
/**
* 更新评论
* @param comment
*/
public void updateComment(Comment comment){
//调用dao
commentRepository.save(comment);
}
/**
* 根据id删除评论
* @param id
*/
public void deleteCommentById(String id){
//调用dao
commentRepository.deleteById(id);
}
/**
* 查询所有评论
* @return
*/
public List findCommentList(){
//调用dao
return commentRepository.findAll();
}
/**
* 根据id查询评论
* @param id
* @return
*/
public Comment findCommentById(String id){
//调用dao
return commentRepository.findById(id).get();
}
public Page findCommentListByParentid(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);
}
}
05 单元测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ArticleApplication.class)
public class CommentServiceTest {
@Autowired
private CommentService commentService;
@Test
public void testFindCommentList() {
List commentList = commentService.findCommentList();
System.out.println(commentList);
}
@Test
public void testFindCommentById() {
Comment commentById = commentService.findCommentById("5f0eb6d74cc07a82bf818c79");
System.out.println(commentById);
}
@Test
public void testSaveComment(){
Comment comment=new Comment();
comment.setArticleid("100000");
comment.setContent("测试添加的数据");
comment.setCreatedatetime(LocalDateTime.now());
comment.setUserid("1001");
comment.setNickname("ylw");
comment.setState("1");
comment.setLikenum(0);
comment.setReplynum(0);
commentService.saveComment(comment);
}
@Test
public void testFindCommentListByParentid() {
Page page = commentService.findCommentListByParentid("3", 1, 2);
System.out.println(page.getTotalElements());
System.out.println(page.getContent());
}
@Test
public void testUpdateCommentLikenum() {
commentService.updateCommentLikenum("5f0eb6d74cc07a82bf818c79");
}
}
测试:
- 测试插入,运行
testSaveComment方法
,在数据库中可以看到有一条数据 - 测试查询,运行
testFindCommentById
方法,可以看到结果能查询出来来 - 测试修改,修改点赞数量,运行
testUpdateCommentLikenum方法
: