SpringDataJPA筆記(10)-動態設置表名

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表的數據

歡迎關注微信交流
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章