MongoDB + SpringBoot

1添加依赖

        
            org.springframework.boot
            spring-boot-starter-data-mongodb
        

2配置文件

# mongodb
spring.data.mongodb.host=10.1.255.20
spring.data.mongodb.port=27019
spring.data.mongodb.database=followup
spring.data.mongodb.username=followup
spring.data.mongodb.password=followup

3编写实体

@Document(collection = "demo_auto")
@Data
@ToString
public class MongoDemoDO implements Serializable {
    @Id
    private String id;

    private String name;

    private String gender;

    private Integer age;
}

spring-data-mongodb中的实体映射是通过MongoMappingConverter这个类实现的。它可以通过注释把java类转换为mongodb的文档。
它有以下几种注释:

@Id - 文档的唯一标识,在mongodb中为ObjectId,它是唯一的,通过时间戳+机器标识+进程ID+自增计数器(确保同一秒内产生的Id不会冲突)构成。

@Document - 把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。@Document(collection=“mongodb”) mongodb对应表

@DBRef - 声明类似于关系数据库的关联关系。ps:暂不支持级联的保存功能。在插入,删除操作时,并不检查对象之间的关联关系就直接操作了

@Indexed - 声明该字段需要索引,建索引可以大大的提高查询效率。

@CompoundIndex - 复合索引的声明,建复合索引可以有效地提高多字段的查询效率。

@GeoSpatialIndexed - 声明该字段为地理信息的索引。

@Transient - 映射忽略的字段,该字段不会保存到mongodb。

@PersistenceConstructor - 声明构造函数,作用是把从数据库取出的数据实例化为对象。该构造函数传入的值为从DBObject中取出的数据。

4 Service层(增删改查)

接口
public interface MongoDBService {
    /**
     * 新增或更新一条记录
     *
     * @param obj
     */
     T save(T objectToSave);

    /**
     * 查询一条记录
     *
     * @param clazz
     * @param query
     * @return
     */
     T findOne(Query query, Class clazz);

    /**
     * 查询所有
     *
     * @param clazz
     * @return
     */
     List findAll(Class clazz);

    /**
     * 根据ID查询一个对象
     *
     * @param clazz
     * @param id
     * @return
     */
     T findById(Object id, Class clazz);

    /**
     * 根据条件查询集合对象
     *
     * @param clazz
     * @param query
     * @return
     */
     List list(Query query, Class clazz);

    /**
     * 分页查询
     */
     Page page(int currentPage, int pageSize, Query query, Class clazz);

    /**
     * 根据条件查询总条数
     *
     * @param clazz
     * @param query
     * @return
     */
     long count(Query query, Class clazz);

    /**
     * 根据条件更新记录
     *
     * @param query 条件
     * @param update 需要更新的字段
     * @param clazz
     * @return
     */
     long update(Query query, Update update, Class clazz);

    /**
     * 根据id删除记录
     *
     * @param clazz
     * @param query
     * @return
     */
     long deleteById(Object id, Class clazz);

}
实现
@Service
public class MongoDBServiceImpl implements MongoDBService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public  T save(T objectToSave) {
        return mongoTemplate.save(objectToSave);
    }

    @Override
    public  T findOne(Query query, Class clazz) {
        return mongoTemplate.findOne(query, clazz);
    }

    @Override
    public  List findAll(Class clazz) {
        return mongoTemplate.findAll(clazz);
    }

    @Override
    public  T findById(Object id, Class clazz) {
        return mongoTemplate.findById(id, clazz);
    }

    @Override
    public  List list(Query query, Class clazz) {
        return mongoTemplate.find(query, clazz);
    }

    @Override
    public  Page page(int currentPage, int pageSize, Query query, Class clazz) {
        query.limit(pageSize);
        query.skip(pageSize * (currentPage - 1));
        Page page = new Page();
        page.setPageNumber(currentPage);
        page.setPageSize(pageSize);
        long total = mongoTemplate.count(query, clazz);
        List list = mongoTemplate.find(query, clazz);
        page.setList(list);
        page.setTotalNumber(total);
        page.setTotalPage(total / pageSize);
        return page;
    }

    @Override
    public  long count(Query query, Class clazz) {
        return mongoTemplate.count(query, clazz);
    }

    @Override
    public  long update(Query query, Update update, Class clazz) {
        return mongoTemplate.updateMulti(query, update, clazz).getModifiedCount();
    }

    @Override
    public  long deleteById(Object id, Class clazz) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.remove(query, clazz).getDeletedCount();
    }@Service
public class MongoDBServiceImpl implements MongoDBService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Override
    public  T save(T objectToSave) {
        return mongoTemplate.save(objectToSave);
    }

    @Override
    public  T findOne(Query query, Class clazz) {
        return mongoTemplate.findOne(query, clazz);
    }

    @Override
    public  List findAll(Class clazz) {
        return mongoTemplate.findAll(clazz);
    }

    @Override
    public  T findById(Object id, Class clazz) {
        return mongoTemplate.findById(id, clazz);
    }

    @Override
    public  List list(Query query, Class clazz) {
        return mongoTemplate.find(query, clazz);
    }

    @Override
    public  Page page(int currentPage, int pageSize, Query query, Class clazz) {
        query.limit(pageSize);
        query.skip(pageSize * (currentPage - 1));
        Page page = new Page();
        page.setPageNumber(currentPage);
        page.setPageSize(pageSize);
        long total = mongoTemplate.count(query, clazz);
        List list = mongoTemplate.find(query, clazz);
        page.setList(list);
        page.setTotalNumber(total);
        page.setTotalPage(total / pageSize);
        return page;
    }

    @Override
    public  long count(Query query, Class clazz) {
        return mongoTemplate.count(query, clazz);
    }

    @Override
    public  long update(Query query, Update update, Class clazz) {
        return mongoTemplate.updateMulti(query, update, clazz).getModifiedCount();
    }

    @Override
    public  long deleteById(Object id, Class clazz) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.remove(query, clazz).getDeletedCount();
    }

单元测试
@SpringBootTest
@Slf4j
class DemoApplicationTests {

    @Resource
    MongoDBService mongoDBService;

    @Test
    void save() {
        MongoDemoDO save = new MongoDemoDO();
        save.setName("戚薇");
        save.setGender("女");
        save.setAge(20);
        MongoDemoDO result = mongoDBService.save(save);
        log.info("ressult:{}", result);
    }

    @Test
    void findById() {
        MongoDemoDO result = mongoDBService.findById("603750ab5f3ee121e806620a", MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void findOne() {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("戚薇"));
        MongoDemoDO result = mongoDBService.findOne(query, MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void findAll() {
        List result = mongoDBService.findAll(MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void list() {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("戚薇"));
        List result = mongoDBService.list(query, MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void page() {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("戚薇"));
        Page result = mongoDBService.page(2, 1, query, MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void count() {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("戚薇"));
        long result = mongoDBService.count(query, MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void remove() {
        long result = mongoDBService.deleteById("603771a05f3ee121e806620b", MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

    @Test
    void update() {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is("戚薇"));
        Update update = new Update();
        update.set("age","12");
        long result = mongoDBService.update(query,update, MongoDemoDO.class);
        log.info("ressult:{}", result);
    }

}

你可能感兴趣的:(MongoDB + SpringBoot)