初次使用java集成mongodb,正好看到集合的行可以设置失效时间,非常适合我们现在的场景,那就用起来吧!!!!
出师未捷身先死,留取丹心照汗青
- 先引入一拨
- 01
- 02
- 03
- 04
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- yml文件配置添加上
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
spring:
data:
mongodb:
host: 127.0.0.1
port: 11001
username: root
password: root
database: bangkaixin
# 权限认证
authentication-database: admin
# 开启索引
auto-index-creation: true
- 实体-------各种注解,只加了用到的几个
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
@Document(collection = "")
//@Document注解最好还是加一下
@Id
private ObjectId _id;
//Mongodb自带的id
/**
* 新建时间
*/
@CreatedDate
@Indexed(name = "deleteAt", expireAfterSeconds = 604800)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime createTime;
/**
* 更新时间
*/
@LastModifiedDate
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private LocalDateTime updateTime;
- 具体调用
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
假装这里有类
@Resource
private MongoTemplate mongoTemplate;
假装这里有方法体
mongoTemplate.save(“这里可以直接放实体或者其它”);
//各种方法
mongoTemplate.findAllAndRemove
.
.
.
.
如果用到索引:
记得开一下
- 01
- 02
- 03
- 04
- 05
spring:
data:
mongodb:
# 开启索引
auto-index-creation: true
当然也有别的方式
可以点这里看一下