SpringBoot + mongodb 整合, 记录网站操作日志,常用查询操作

avatar 2018年09月03日20:39:48 6 8374 views
博主分享免费Java教学视频,B站账号:Java刘哥
mongodb 是一种文档型数据库。跟 Redis 一样是非关系型数据库,Redis 属于那种小而快的数据库,常常用作缓存。 而如果我们需要存一些类似于日志的那种,可以尝试用 mongodb (当然也有人用 MySQL,就是有点慢)。我们尝试用 mongodb 来存储博客的日志信息。 本文主要介绍 SpringBoot 和 mongodb 整合,和基本的查询操作。  

一、依赖和配置

创建 springboot 项目,引入 web 和 lombok,然后再添加 mongodb 依赖 1、pom.xml
  1. <!--mongodb-->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-data-mongodb</artifactId>
  5. </dependency>
类似 Spring Data JPA   2、application.properties
  1. spring.data.mongodb.uri=mongodb://localhost:27017/saysky
saysky是数据库名称,确保你本地启动了 mongodb  

二、代码实例

1、日志实体
  1. package com.liuyanzhao.mongodb.model;
  2. import lombok.Data;
  3. import java.util.Date;
  4. /**
  5.  * 日志
  6.  * @author 言曌
  7.  * @date 2018/9/3 20:00
  8.  */
  9. @Data
  10. public class Log {
  11.     private Long id;
  12.     private Long userId;
  13.     private Integer type;
  14.     private String url;
  15.     private String desc;
  16.     private Date createTime;
  17. }
  2、LogRepository
  1. package com.liuyanzhao.mongodb.dao;
  2. import com.liuyanzhao.mongodb.model.Log;
  3. import org.springframework.data.domain.Page;
  4. import org.springframework.data.domain.Pageable;
  5. import org.springframework.data.mongodb.repository.MongoRepository;
  6. import org.springframework.stereotype.Repository;
  7. import java.util.Date;
  8. import java.util.List;
  9. /**
  10.  * @author 言曌
  11.  * @date 2018/9/3 14:17
  12.  */
  13. @Repository
  14. public interface LogRepository extends  <Log, Long> {
  15.     /**
  16.      * 根据用户ID查询
  17.      * @param userId
  18.      * @return
  19.      */
  20.     List<Log> findByUserId(Long userId);
  21.     /**
  22.      * 根据描述查询
  23.      * @param desc
  24.      * @return
  25.      */
  26.     List<Log> findByDesc(String desc);
  27.     /**
  28.      * 根据创建日期范围查询
  29.      * @param startTime
  30.      * @param endTime
  31.      * @return
  32.      */
  33.     List<Log> findByCreateTimeBetween(Date startTime, Date endTime);
  34.     /**
  35.      * 根据描述查询
  36.      * 分页查询
  37.      * @param desc
  38.      * @return
  39.      */
  40.     Page<Log> findByDesc(String desc, Pageable pageable);
  41.     /**
  42.      * 根据创建日期范围查询
  43.      * 分页查询
  44.      * @param startTime
  45.      * @param endTime
  46.      * @return
  47.      */
  48.     Page<Log> findByCreateTimeBetween(Date startTime, Date endTime,Pageable pageable);
  49. }
  3、测试类
  1. package com.liuyanzhao.mongodb.dao;
  2. import com.liuyanzhao.mongodb.model.Log;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.data.domain.Page;
  8. import org.springframework.data.domain.PageRequest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import java.util.Date;
  11. /**
  12.  * @author 言曌
  13.  * @date 2018/9/3 14:21
  14.  */
  15. @SpringBootTest
  16. @RunWith(SpringRunner.class)
  17. public class LogRepositoryTest {
  18.     @Autowired
  19.     private LogRepository logRepository;
  20.     @Test
  21.     public void save() {
  22.         Log log = new Log();
  23.         log.setId(7L);
  24.         log.setType(1);
  25.         log.setDesc("更新用户");
  26.         log.setUserId(10002L);
  27.         log.setUrl("/user/update");
  28.         log.setCreateTime(new Date());
  29.         logRepository.save(log);
  30.     }
  31.     @Test
  32.     public void findById() {
  33.         Log Log = logRepository.findById(1L).get();
  34.         System.out.println(Log);
  35.     }
  36.     @Test
  37.     public void findByDes() {
  38.         //不分页
  39. //        List<Log> LogList = logRepository.findByDesc("添加用户");
  40. //        System.out.println(LogList);
  41.         //分页查询
  42.         //查询第1页,每页显示2条
  43.         PageRequest pageRequest = new PageRequest(0,2);
  44.         Page<Log> logPage = logRepository.findByDesc("添加用户",pageRequest);
  45.         System.out.println(logPage);
  46.     }
  47.     @Test
  48.     public void findByCreateTimeBetween() {
  49.         //根据时间区间查询
  50.         //不分页
  51.         Date createdAtStart = new Date(1535974057016L);
  52.         Date createdAtEnd = new Date(1535974145009L);
  53. //        List<Log> LogList = logRepository.findByCreateTimeBetween(createdAtStart,createdAtEnd);
  54. //        System.out.println(LogList);
  55.         //分页查询
  56.         //查询第1页,每页显示2条
  57.         PageRequest pageRequest = new PageRequest(0,2);
  58.         Page<Log> logPage = logRepository.findByCreateTimeBetween(createdAtStart,createdAtEnd,pageRequest);
  59.         System.out.println(logPage);
  60.     }
  61. }
  我们通过mongodb可视化工具可以看到数据  

三、更多查询

因为引入的 MongoRepository 是一种 JPA 框架,所以增删改查都很容易。 可以参考 Spring Data JPA 方法命名规范
方法关键字 示例 等价于SQL
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,findByFirstnameIs,findByFirstnameEquals … where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age <= ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1(参数绑定附加%)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1(参数与预先绑定%)
Containing findByFirstnameContaining … where x.firstname like ?1(参数绑定%)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection ages) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0