SpringDataMongoDB

SpringData家族成员之一,用于操作MongoDb的持久层框架,封装了底层的mongodbdriver。
官网主页: https://projects.spring.io/spring-data-mongodb/

(1) pom.xml引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring‐boot‐starter‐data‐mongodb</artifactId>       
</dependency> 

(2) 创建application.yml

server: 
  port: 9006
spring: 
  application:  
    name: tensquare-spit #指定服务名
  data:
    mongodb:
      host: 122.51.65.35
      database: spitdb

(3) 创建启动类

@SpringBootApplication
@EnableEurekaClient
public class SpitApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpitApplication.class, args);
    }

    @Bean
    public IdWorker idWorker(){
        return new IdWorker(1, 1);
    }
}

(4) 创建实体类

@Data
@Accessors(chain = true)
public class Spit implements Serializable {

    @Id
    private String _id;
    private String content;
    private Date publishtime;
    private String userid;
    private String nickname;
    private Integer visits;
    private Integer thumbup;
    private Integer share;
    private Integer comment;
    private String state;
    private String parentid;
}

(5) 创建数据访问接口

创建dao包,包下创建接口


public interface SpitDao extends MongoRepository<Spit, String> {

    //根据上级ID查询吐槽数据
    public Page<Spit> findByParentid(String parentid, Pageable pageable);
}

(6) 创建业务逻辑类

创建service包,包下创建类

@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    /** * 查询全部 * @return */
    public List<Spit> findAll(){
        return spitDao.findAll();
    }

    /** * 根据id查询 * @param id * @return */
    public Spit findById(String id){
        return spitDao.findById(id).get();
    }

    /** * 保存 * @param spit */
    public void save(Spit spit){
        spit.set_id(idWorker.nextId()+"");
        spit.setPublishtime(new Date());//发布日期
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");;//状态
        //如果添加的吐槽,有父节点,那么吐槽的父节点吐槽回复数要加一
        if (!StringUtils.isEmpty(spit.getParentid())){//如果存在上级ID,评论
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update = new Update();
            update.inc("comment", 1);
            mongoTemplate.updateFirst(query, update, "spit");
        }
        spitDao.save(spit);
    }

    /** * 修改 * @param spit */
    public void update(Spit spit){
        spitDao.save(spit);
    }

    /** * 根据id删除 * @param id */
    public void deleteById(String id){
        spitDao.deleteById(id);
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务