SpringDataJPA笔记(10)-动态设置表名
在实际使用中可能会遇到需要动态设置表名的情况,特别是通常在后台管理系统里面,总有一些相似的功能需要抽象出来写一些公共的方法,以减少代码开发量,降低重复劳动
首先看BaseRepository的代码
@NoRepositoryBean public interface BaseRepository<T, ID extends Serializable> extends JpaRepository<T, ID>, JpaSpecificationExecutor<T>, Serializable { @Transactional @Modifying(clearAutomatically = true) @Query("update #{#entityName} t set t.age=?2 where t.id = ?1") int updateAge(ID id, int age); @Query("select t.id from #{#entityName} t ") List<ID> findIds(); }
然后创建一个BaseController
@Slf4j public class BaseController<R extends BaseRepository<T, ID>, T extends AnimalEntity, ID extends Serializable> { @Autowired private R repository; @ApiOperation(value = "baseAll", httpMethod = "GET") @GetMapping(value = "/base/all") public List<T> baseAll() { log.info("BaseController list"); return repository.findAll(); } @ApiOperation(value = "update age by id", httpMethod = "GET") @GetMapping(value = "/update/age/{id}") public T baseAll(@PathVariable ID id, @RequestParam int age) { log.info("BaseController list"); repository.updateAge(id, age); Optional<T> optional = repository.findById(id); if(optional.isPresent()){ return optional.get(); } return null; } @ApiOperation(value = "base ids", httpMethod = "GET") @GetMapping(value = "/base/ids") public List<ID> findIds() { log.info("BaseController list"); return repository.findIds(); } }
在分别创建两个不同的controller
ChapterTenCatController
@RestController @RequestMapping("/chapter/ten/cat") public class ChapterTenCatController extends BaseController<CatRepository, CatEntity, Long> { }
ChapterTenDogController
@RestController @RequestMapping("/chapter/ten/dog") public class ChapterTenDogController extends BaseController<DogRepository, DogEntity, Long> { }
运行代码之后,查看swagger-ui的页面
可以看到多了两个controller
打开这两个controller,看到里面的接口是在BaseController里面写的
分别运行里面的接口,可以看到是分别查询和更新了cat表和dog表的数据
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句