MongoDB笔记(八) —— SpringBoot使用MongoDB

加入pom依赖:

<!--mongodb 依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

新建实体类NotifyMsg:

/**
 * 通知消息对象
 *
 * @author zhaohaibin
 * @Document(collection="notify_msg") 表示:操作的集合为:notify_msg。
 */
@Document(collection = "notify_msg")
@Data
public class NotifyMsg implements Serializable {

    private static final long serialVersionUID = -8412725291327994826L;

    private String id;

    /**
     * 消息类型
     */
    private String notifyType;

    /**
     * 消息单号
     */
    private String notifyNo;

    /**
     * 消息通知日期
     */
    private String notifyDate;

    /**
     * 消息体
     *
     * @Field("notifyMsg") - 可指定存储时的字段名
     */
    private String notifyMsg;

    /**
     * 创建时间
     */
    private Date gmtCreate;
}

添加mongodb配置:

#mongodb
# 单机模式 mongodb://name:pass@ip:port/database
# 集群模式 mongodb://user:pwd@ip1:port1,ip2:port2/database
spring:
  data:
    mongodb:
      uri: mongodb://127.0.0.1:27017/learning

更新启动类:

/**
 * 启动类
 *
 * @author zhaohaibin
 * @EnableMongoRepositories(basePackages="com.zhb.dao") - 当有些dao不在default page下时 可通过此方法进行注册扫描包
 */
@SpringBootApplication
@EnableMongoAuditing
public class MongoDBDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MongoDBDemoApplication.class, args);
    }

}

注意:

当使用MongoRepositories时,可能有些MongoRepositories类不在默认的包路径(启动类路径)下,可使用@EnableMongoRepositories的basePackages需要扫描的路径信息。

若都在默认的包路径下,可以不加此注解的。

新建服务接口NotifyMsgService和实现类NotifyMsgServiceImpl:

/**
 * 接口服务
 *
 * @author zhaohaibin
 */
public interface NotifyMsgService {

    /**
     * 保存数据
     */
    NotifyMsg saveNotifyMsg(NotifyMsg msg);

    /**
     * 根据消息号查找
     */
    NotifyMsg findNotifyMsgByNo(String notifyNo);

    /**
     * 根据消息日期查找
     */
    List<NotifyMsg> findNotifyMsgByDate(String notifyDate);

    /**
     * 根据id进行删除 返回删除的对象
     */
    NotifyMsg delNotifyMsgById(String id);

}
/**
 * MongoDB Template访问实现
 *
 * @author zhaohaibin
 */
@Service
@Slf4j
public class NotifyMsgServiceImpl implements NotifyMsgService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public NotifyMsg saveNotifyMsg(NotifyMsg msg) {
        // 使用 save和insert都可以进行插入
        // 区别:当存在"_id"时
        // insert 插入已经存在的id时 会异常
        // save 则会进行更新
        // 简单来说 save 就是不存在插入 存在更新
        mongoTemplate.insert(msg);
        mongoTemplate.save(msg);

        return msg;
    }

    @Override
    public NotifyMsg findNotifyMsgByNo(String notifyNo) {
        // 根据Criteria 改造查询条件
        Query query = new Query(Criteria.where("notifyNo").is(notifyNo));
        return mongoTemplate.findOne(query, NotifyMsg.class);
    }

    @Override
    public List<NotifyMsg> findNotifyMsgByDate(String notifyDate) {
        // 查找 notifyDate 根据Criteria 改造查询条件
        Query query = new Query(Criteria.where("notifyDate").is(notifyDate));
        return mongoTemplate.find(query, NotifyMsg.class);
    }

    @Override
    public NotifyMsg delNotifyMsgById(String id) {
        // 查找 id 根据Criteria 改造查询条件
        Query query = new Query(Criteria.where("id").is(id));
        return mongoTemplate.findAndRemove(query, NotifyMsg.class);
    }
}

新建控制器MongodbTemplateController:

/**
 * mongodbTemplate 示例
 *
 * @author zhaohaibin
 */
@RestController
@RequestMapping("/template")
@Slf4j
public class MongodbTemplateController {

    @Autowired
    NotifyMsgService notifyMsgService;

    @PostMapping("/add")
    public NotifyMsg add(NotifyMsg msg) {
        log.info("mongodbTemplate方式新增:{}", msg);
        return notifyMsgService.saveNotifyMsg(msg);
    }

    @PostMapping("del/{id}")
    public NotifyMsg del(@PathVariable String id) {
        log.info("mongodbTemplate方式删除:{}", id);
        return notifyMsgService.delNotifyMsgById(id);
    }

    @GetMapping("/find/{no}")
    public NotifyMsg findNotifyMsgByNo(@PathVariable String no) {
        log.info("mongodbTemplate方式查找:notifyNo-{}", no);
        return notifyMsgService.findNotifyMsgByNo(no);
    }

    @GetMapping("/find/list/{date}")
    public List<NotifyMsg> findNotifyMsgByDate(@PathVariable String date) {
        log.info("mongodbTemplate方式查找:notifyDate-{}", date);
        return notifyMsgService.findNotifyMsgByDate(date);
    }
}

运行访问:

地址(add):localhost:8080/template/add

参数(form-data):

notifyType:消息类型
notifyNo:20200101000004
notifyDate:20200101
notifyMsg:{“code”:“001”}

可视化工具(learning.notify_msg):

/** 
* Paste one or more documents here
*/
{
  	"_id":ObjectId("5e7abcaeefd3c54810dc93e8"),
    "notifyType": "消息类型",
    "notifyNo": "20200101000000",
    "notifyDate": "20200101",
    "notifyMsg": "{\"code\":\"001\"}",
    "_class": "com.zhb.demo.entity.NotifyMsg"
}

findList:localhost:8080/template/find/list/20200101

find:localhost:8080/template/find/20200101000000

del:localhost:8080/template/del/5e7abcaeefd3c54810dc93e8

自定义资源访问接口NotifyMsgDao:

/**
 * MongoDBRepository 示例
 *
 * @author zhaohaibin
 */
public interface NotifyMsgDao extends MongoRepository<NotifyMsg, String> {

    /**
     * 根据消息号进行查询
     *
     * @param notifyNo
     * @return
     */
    NotifyMsg findByNotifyNo(String notifyNo);

    /**
     * 根据日期查询 自定义查询
     * <p>
     * 需要注意:查询的语法结构,同时这里和`jpa`不一样的地方是,第一个索引值从0开始
     */
    @Query("{'notifyDate':?0}")
    Page<NotifyMsg> queryBySql(String notifyDate, Pageable pageable);
}

Query更多使用说明:

https://docs.spring.io/spring-data/mongodb/docs/1.10.14.RELEASE/reference/html/#mongodb.repositories.queries

Keyword Sample Logical result
After findByBirthdateAfter(Date date) {"birthdate" : {"$gt" : date}}
GreaterThan findByAgeGreaterThan(int age) {"age" : {"$gt" : age}}
GreaterThanEqual findByAgeGreaterThanEqual(int age) {"age" : {"$gte" : age}}
Before findByBirthdateBefore(Date date) {"birthdate" : {"$lt" : date}}
LessThan findByAgeLessThan(int age) {"age" : {"$lt" : age}}
LessThanEqual findByAgeLessThanEqual(int age) {"age" : {"$lte" : age}}
Between findByAgeBetween(int from, int to) {"age" : {"$gt" : from, "$lt" : to}}
In findByAgeIn(Collection ages) {"age" : {"$in" : [ages…]}}
NotIn findByAgeNotIn(Collection ages) {"age" : {"$nin" : [ages…]}}
IsNotNull, NotNull findByFirstnameNotNull() {"firstname" : {"$ne" : null}}
IsNull, Null findByFirstnameNull() {"firstname" : null}
Like, StartingWith, EndingWith findByFirstnameLike(String name) {"firstname" : name} (name as regex)
NotLike, IsNotLike findByFirstnameNotLike(String name) {"firstname" : { "$not" : name }} (name as regex)
Containing on String findByFirstnameContaining(String name) {"firstname" : name} (name as regex)
NotContaining on String findByFirstnameNotContaining(String name) {"firstname" : { "$not" : name}} (name as regex)
Containing on Collection findByAddressesContaining(Address address) {"addresses" : { "$in" : address}}
NotContaining on Collection findByAddressesNotContaining(Address address) {"addresses" : { "$not" : { "$in" : address}}}
Regex findByFirstnameRegex(String firstname) {"firstname" : {"$regex" : firstname }}
(No keyword) findByFirstname(String name) {"firstname" : name}
Not findByFirstnameNot(String name) {"firstname" : {"$ne" : name}}
Near findByLocationNear(Point point) {"location" : {"$near" : [x,y]}}
Near findByLocationNear(Point point, Distance max) {"location" : {"$near" : [x,y], "$maxDistance" : max}}
Near findByLocationNear(Point point, Distance min, Distance max) {"location" : {"$near" : [x,y], "$minDistance" : min, "$maxDistance" : max}}
Within findByLocationWithin(Circle circle) {"location" : {"$geoWithin" : {"$center" : [ [x, y], distance]}}}
Within findByLocationWithin(Box box) {"location" : {"$geoWithin" : {"$box" : [ [x1, y1], x2, y2]}}}
IsTrue, True findByActiveIsTrue() {"active" : true}
IsFalse, False findByActiveIsFalse() {"active" : false}
Exists findByLocationExists(boolean exists) {"location" : {"$exists" : exists }}

更新controller和service:

controller:

@GetMapping("/find/sql/{date}")
public Page<NotifyMsg> queryBySql(@PathVariable String date){
    Pageable pageable = new PageRequest(0, 10);
    log.info("repository方式分页sql查找日期:{}", date);
    return notifyMsgService.queryBySql(date, pageable);
}

service接口:

/**
 * 分页查询
 *
 * @param date
 * @param pageable
 * @return
 */
Page<NotifyMsg> queryBySql(String date, Pageable pageable);

service实现:

@Autowired
NotifyMsgDao notifyMsgDao;

@Override
public Page<NotifyMsg> queryBySql(String date, Pageable pageable) {
    return notifyMsgDao.queryBySql(date,pageable);
}

重启后请求:

localhost:8080/template/find/sql/20200101

返回:

{
    "content": [
        {
            "id": "5e7ac4d1efd3c54810dc93e9",
            "notifyType": "消息类型",
            "notifyNo": "20200101000001",
            "notifyDate": "20200101",
            "notifyMsg": "{\"code\":\"001\"}",
            "gmtCreate": null
        },
        {
            "id": "5e7ac4d5efd3c54810dc93ea",
            "notifyType": "消息类型",
            "notifyNo": "20200101000002",
            "notifyDate": "20200101",
            "notifyMsg": "{\"code\":\"001\"}",
            "gmtCreate": null
        },
        {
            "id": "5e7ac4d8efd3c54810dc93eb",
            "notifyType": "消息类型",
            "notifyNo": "20200101000003",
            "notifyDate": "20200101",
            "notifyMsg": "{\"code\":\"001\"}",
            "gmtCreate": null
        },
        {
            "id": "5e7ac4dbefd3c54810dc93ec",
            "notifyType": "消息类型",
            "notifyNo": "20200101000004",
            "notifyDate": "20200101",
            "notifyMsg": "{\"code\":\"001\"}",
            "gmtCreate": null
        }
    ],
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageSize": 10,
        "pageNumber": 0,
        "paged": true,
        "unpaged": false
    },
    "last": true,
    "totalPages": 1,
    "totalElements": 4,
    "size": 10,
    "numberOfElements": 4,
    "first": true,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "empty": false
}

参考:

SpringBoot | 第三十一章:MongoDB的集成和使用

发布了90 篇原创文章 · 获赞 12 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/u012382791/article/details/105425585
今日推荐