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 注入到实现类里