SpringDataJPA笔记(10)-动态设置表名
在实际使用中可能会遇到需要动态设置表名的情况,特别是通常在后台管理系统里面,总有一些相似的功能需要抽象出来写一些公共的方法,以减少代码开发量,降低重复劳动
首先看BaseRepository的代码
代码语言:javascript复制@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
代码语言:javascript复制@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
代码语言:javascript复制@RestController
@RequestMapping("/chapter/ten/cat")
public class ChapterTenCatController extends BaseController<CatRepository, CatEntity, Long> {
}
ChapterTenDogController
代码语言:javascript复制@RestController
@RequestMapping("/chapter/ten/dog")
public class ChapterTenDogController extends BaseController<DogRepository, DogEntity, Long> {
}
运行代码之后,查看swagger-ui的页面
可以看到多了两个controller
打开这两个controller,看到里面的接口是在BaseController里面写的
分别运行里面的接口,可以看到是分别查询和更新了cat表和dog表的数据