|
java增删改查
springBoot导包
<dependencies>
<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-data-mongodb</artifactId>
</dependency>
</dependencies>
然后引用框架
看源码可知

显然dao层继承这个 MongoRepository 就能实现单表crud
T 写 表对应的entitle 类映射集合字段 这里是 Comment
/**
* 文章评论实体类
*/
//把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
//@Document(collection="mongodb 对应 collection 名")
// 若未加 @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.....
ID 替换成该集合 ID字段的类型 这里是String
//评论的dao接口
public interface CommentRepository extends MongoRepository<Comment,String> {
//根据父id,查询子评论的分页列表
Page<Comment> findByParentid(String parentid, Pageable pageable);
}
service 层直接注入dao层 XXXRepository 然后 . 根据方法提示能实现基础的crud了

同时做分页,排序,搜索就有点麻烦了
我们引入该框架的另外三个强大的工具类组合使用
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
总体而言和spring data JPA大同小异
以下是简单的运用方式
/**
* 实现组合 条件 分页 排序 查询
* Criteria与mongoTemplate的运用
* */
@Test
public void findCommentListPageByCriteria(){
Comment comment = new Comment();
comment.setUserid("1005");
comment.setNickname("凯撒大帝");
ArrayList<String> list1 = new ArrayList<>();
list1.add("1005");
list1.add("1001");
list1.add("1003");
Criteria criteria = Criteria
// .where("nickname")
// .is(comment.getNickname())
.where("userid")
.in(list1);
criteria.and("nickname").is(comment.getNickname());
Query query=Query.query(criteria);
int page = 1;
int size = 3;
query.skip(page).limit(size);
Sort sort=new Sort(Sort.Direction.DESC,"createTime");
query.with(sort);
// List<Comment> list= commentService.findCommentListPageBy(query);
// System.out.println(list);
List<Comment> comments = mongoTemplate.find(query, Comment.class,"comment");
System.out.println("mongoDB组合查询数据成功,集合为\"comment\",文档为:");
System.out.println(comment);
}
补充 特定字段查询与过滤
query.fields().include(“字段”); //包含该字段 query.fields().exclude(“字段”);//不包含该字段 |