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表的数据
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有