🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**1. 实体类建立关系** ```java public class Country { //country 对应 Province.country 属性名 @OneToMany(mappedBy = "country", fetch = FetchType.EAGER) private List<Province> provinceList; } ``` ```java public class Province { //Country -> Province 是一对多,反过来 Province -> Country 就是多对一 @ManyToOne(targetEntity = Country.class) //country_id 对应 Country.id 属性名 //将会在 Province 表中建立 country_id 的物理外键 @JoinColumn(name = "country_id", referencedColumnName = "id") private Country country; } ``` **2. Specification多表查询** ```java /** * select c.* from country c left join province p on c.id=p.country_id * where c.continent=亚洲 and p.level=1 */ @Test public void example02() { Specification<Country> spec = (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(1); //provinceList 对应 Country.provinceList 属性名 Join<Country, Province> left = root.join("provinceList", JoinType.LEFT); predicates.add(cb.equal(root.get("continent").as(String.class), "亚洲")); //level 对应 Province.level 属性名 predicates.add(cb.equal(left.get("level").as(Integer.class), 1)); return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction(); }; List<Country> countryList = countryRepository.findAll(spec); System.out.println(countryList.size()); } ``` ```java /** * select p.* from province p left join country c on p.country_id=c.id * where p.level=1 and c.name=中国 */ @Test public void example01() { Specification<Province> spec = (root, query, cb) -> { List<Predicate> predicates = new ArrayList<>(1); Join<Province, Country> left = root.join("country", JoinType.LEFT); predicates.add(cb.equal(root.get("level").as(Integer.class), 1)); predicates.add(cb.equal(left.get("name").as(String.class), "中国")); return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction(); }; List<Province> provinceList = provinceRepository.findAll(spec); System.out.println(provinceList.size()); } ```