Spring Data JPA如何有选择性的暴露方法
1、首先我们创建一稍僚敉视个自定义的Repository接口MyBaseRepository,该接口使用泛型去接收参数,在该接口中只定义保存save和单个查询findOne方法,在该接口在添加@绿覆冗猩NoRepositoryBean注解,该注解使用这个接口不会被当做方法的接口扫描到。@NoRepositoryBeanpublic interface MyBaseRepository<T, ID extends Serializable> extends Repository<T, ID> { T findOne(ID id); T save(T entity);}
2、接下来创建TestCustomRepository继承自定义的MyBaseRepository,然后在该接口中我们根据方法名创建一个查询的方法findByAge(),如下图所示。public interface TestCustomRepository extends MyBaseRepository<User, Long> { List<User> findByAge(Integer age);}
3、接下来我们创建一个TestCustomController类,在该类中定义保存数据和查询数据的方法,我们在数据库中使用的还是User表,我们先调用save()方法保存数据,然后便是分别根据id和age进行查询的方法,如下图所示。@PostMapping(path = "/add")public String addNewUser(@RequestParam String name, @RequestParam Integer age) { User n = new User(); n.setName(name); n.setAge(age); User result = testCustomRepository.save(n); return JSON.toJSONString(result);}@GetMapping(path = "/info")public User findOne(@RequestParam Long id) { return testCustomRepository.findOne(id);}@GetMapping(path = "/age")public List<User> findByAge(@RequestParam Integer age) { return test
4、我们在使用testCustomRepository进行方法调用时可以看到,可以直接点出来的方法只有定义好的3个,其他的是通用的方法。
5、服务启动后,利用postman进行调用,我们启动服务使用debug的方式,这样便可以在断点中查看方法调用的过程,根据以下调试的结果我们可以知道,Repository的实现类是SimpleJpaRepository,以及在根据方法名进行调用的过程中使用了动态代理的模式。
6、下图为postman中分别请求保存,根据id进行查询和根据年龄进行查询的调用结果。