SpringDataJPA筆記(5)-子查詢

SpringDataJPA-子查詢

子查詢也是一種視圖查詢

在數據庫實際使用的時候,爲了一些業務的設計,有些時候我們需要映射視圖到實體,這個時候就可以使用Subselect註解來標註一個視圖類

STEP1 構建視圖類

@Data
@Entity
@Subselect("select d.id as id, d.name as dog_name, c.name as cat_name from dog_tb d left join cat_tb c on d.id=c.id")
@Synchronize({"dog_tb", "cat_tb"})
public class SubSelectEntity implements Serializable {

    private static final long serialVersionUID = -3795682088296075408L;
    @Id
    private Long id;

    private String dogName;

    private String catName;
}

@Subselect

子查詢的註解,裏面是原生的sql語句

@Synchronize

需要同步的表,如果表變動了,查詢視圖會更新這個數據

備註:可以使用@Immutable 來標註這個類不可以修改,因爲視圖是可讀不可寫的,修改數據需要修改對應表的數據

STEP2 構建repository接口

和普通的實體類構建repository接口一樣

public interface SubSelectRepository extends JpaRepository<SubSelectEntity, Long>, JpaSpecificationExecutor<SubSelectEntity>, Serializable {
}

STEP3 使用

使用也和普通的實體類的使用方法一致,就不詳細寫了,寫兩個方法測試一下

@Slf4j
@RestController
@RequestMapping("/chapter/five")
public class ChapterFiveController {

    @Autowired
    private SubSelectRepository subSelectRepository;

    @ApiOperation(value = "findAll", httpMethod = "GET")
    @GetMapping("/find")
    public List<SubSelectEntity> findAll() {
        return subSelectRepository.findAll();
    }

    @ApiOperation(value = "findPage", httpMethod = "GET")
    @GetMapping("/page")
    public Page<SubSelectEntity> findPage(@RequestParam int pageSize, @RequestParam int pageNum) {
        Pageable pageable = PageRequest.of(pageNum, pageSize);
        return subSelectRepository.findAll(pageable);
    }
}

源碼參考 GITHUB
歡迎關注微信交流
在這裏插入圖片描述

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