多表關(guān)聯(lián)常常通過創(chuàng)建數(shù)據(jù)庫視圖的方式來解決,其實(shí)也可以使用虛擬視圖,維護(hù)更為方便。
表person和表id_card通過外鍵id_card_id關(guān)聯(lián)。
創(chuàng)建虛擬視圖PersonIdCard類:
數(shù)據(jù)庫訪問PersonIdCardRepository類:@Entity @Immutable @Subselect("SELECT p.id id, p.name name, p.age age, ic.number number " + "FROM person p " + "LEFT JOIN id_card ic " + "ON p.id_card_id=ic.id") public class PersonIdCard { @Id private Long id; private String name; private Integer age; private String number;
// getter and setter
}
public interface PersonIdCardRepository extends JpaRepository<PersonIdCard, Long>, JpaSpecificationExecutor<PersonIdCard> {
}
查詢年齡大于20的人。public List<PersonIdCard> findAll(SearchRequest request) {
Specification<PersonIdCard> specification = new Specifications<PersonIdCard>()
.gt(Object.nonNull(request.getAge()), "age", 20)
.build();
return personRepository.findAll(specification);
}
更多建議: