spring data mongodb 使用 Repository/mongoTemplate

spring data mongodb 有2种使用方式:

第一种是Repository,能够直接继承MongoRepository等接口,使用CRUD等方法和JPA的方法而不用写实现

第二种就是使用mongoTemplate,需要自己写实现类,增删改查可以自己控制

我们项目中可以同时使用两种方式:


准备:

实体类Role:

@Document(collection = "role")
public class Role extends Contact {
    @Id
    private String id;

    private String name;

    private int age;

1.需要使用mongoTemplate的接口:

public interface RoleRepositoryEnhance {
    saveEntity(Role role){
}
2.实现类(这个类名是固定的)
public class RoleRepositoryImpl implements RoleRepositoryEnhance {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public void saveEntity(Role role){
        mongoTemplate.save(role);
    }

}

3.Repository

@Repository
public interface RoleRepository extends MongoRepository<Role,String>,RoleRepositoryEnhance {
}

此时就可以注入RoleRepository,然后使用Repository的JPA方法 和 我们自定义使用mongoTemplate的方法了

原理:

spring 注入这个接口的实现类的时候,遇到RoleRepositoryEnhance 这个接口,会自动去寻找RoleRepositoryImpl这个实现类,也就是类名是RoleRepository+Impl 注入到实现类里



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值