mongoDB在springboot项目中进行增删改查的两种方式
MongoTemplate,直接注入即可使用
有save和insert都为保存,区别在于save会在数据相同时进行修改
@Autowired
private MongoTemplate mongoTemplate;
//创建数据库集合,集合中的每一条数据为文档
MongoCollection<Document> collection = mongoTemplate.createCollection(ApComment.class);
mongoTemplate.dropCollection(ApComment.class);
//原生查询---------------------
mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(Comment.getId())),CommentLike.class);
MongoRepository
定义数据层接口,可以保证三层架构
repository包
@Repository
//第一个参数为与数据库映射的类,第二个为主键id
public interface CommentRepository extends MongoRepository<Comment, String> {
public List<ApComment> findByContentLike(String content);
//方法可以自己定义
public List<ApComment> findByContentLikeAndLikesGreaterThan(String content,Integer likes);
public Page<ApComment> findByContentLike(String content, Pageable pageable);
}