MongnDB 自动装配

场景:数据库表设计时,一般都会有一些公用字段,例如创建人、创建时间等。使用过 MyBatis-Plus 的同学都知道,这些公共字段都是可以自动装配的,意思是只要配置好,不需要每个方法都写一遍,下文就是对 MongnDB 做自动装配
 
实体

公共实体 BasePO,这里设计了 id、逻辑删除标记、创建者id、创建时间、最后更新者id、最后更新时间

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class BasePO implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "主键")
    @Id
    private Long id;

    @ApiModelProperty(value = "逻辑删除标记")
    private String deleteFlag;

    @ApiModelProperty(value = "创建者id")
    private Long createdBy;

    @ApiModelProperty(value = "创建时间")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime creationDate;

    @ApiModelProperty(value = "最后更新者id")
    private Long lastUpdatedBy;

    @ApiModelProperty(value = "最后更新时间")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastUpdateDate;

}

操作实体 testPO

@Data
@Document(collection = "test")
public class TestPO extends BasePO {

    /**
     * 名称
     */
    private String name;

    /**
     * 描述
     */
    private String description;

}

 
字段处理监听器

  • onBeforeConvert:在 object 被MongoConverter转换为Document之前,在MongoTemplate insert,insertList和save操作中调用。
  • onBeforeSave: 在将Document插入或保存在数据库中之前,请在MongoTemplate insert,insertList和save操作中调用。
  • onAfterSave: 在将Document插入或保存在数据库中之后,在MongoTemplate insert,insertList和save操作中调用。
  • onAfterLoad: 从数据库中检索Document后,在MongoTemplate find,findAndRemove,findOne和getCollection方法中调用。
  • onAfterConvert: 从数据库中检索到Document后,在MongoTemplate find,findAndRemove,findOne和getCollection方法中调用被转换为 POJO
@Configuration
public class CommonFieldsEventListener extends AbstractMongoEventListener {

    @Override
    public void onBeforeConvert(BeforeConvertEvent event) {
        Object source = event.getSource();
        if (source instanceof BasePO) {
            LocalDateTime now = LocalDateTime.now();
            BasePO entity = BasePO.class.cast(source);

            entity.setLastUpdateDate(now);
            entity.setLastUpdatedBy(getUserId());

            /* 使用随机数做 id */
            if(entity.getId() == null){
                entity.setId(RandomUtils.nextLong());
            }

            if (entity.getCreationDate() == null) {
                entity.setCreationDate(now);
                entity.setCreatedBy(getUserId());
                entity.setDeleteFlag("N");
            }
        }
    }

    /**
     * 获取当前用户 id
     * @return  当前用户 id
     */
    private Long getUserId(){
        return 1L;
    }
}

新增

TestPO testPO = new TestPO("name" , "description" );
mongoTemplate.insert(testPO);

更新

TestPO testPO = new TestPO("name" , "description" );
mongoTemplate.save(testPO);

save 更新时,发现最后修改日期和最后修改人并没有更新

解决方案:

  • 先用 id 查询出数据详情
  • 再用 hutool 工具把查询出来的数据,复制到传参里
  • 空数据不处理,setIgnoreNullValue(true)
  • 最后调用 save 方法
TestPO po = mongoTemplate.findById(testPO.getId(),TestPO.class);
BeanUtil.copyProperties(po, testPO, CopyOptions.create().setIgnoreNullValue(true));
mongoTemplate.save(testPO);

引入 hutool

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.13</version>
</dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值