graph用来处理jpa查询一对多关系时多次查询数据库的问题,使用后可将数据一次全部查出
使用的步骤和方法
1、在entity中加入注解
在class上加注解
@NamedEntityGraph(name = "people.all",
attributeNodes = {@NamedAttributeNode("fruits")})
public class People{
@Id
private Integer id;
@OneToMany(targetEntity = Fruit.class)
@JoinColumn(name = "peopleId", referencedColumnName = "id")
private List<Fruit> fruits;
}
2、在Repository重写查询接口,加注解,使graph生效
public interface PeopleRepository extends JpaRepository<People, Integer>{
@EntityGraph(value = "people.all", type = EntityGraph.EntityGraphType.FETCH)
List<People> findAll(@NonNull Predicate predicate);
}
3、需要一次查询出 @OneToMany数据处调用
@Autowired
private PeopleRepository peopleRepository ;
public Iterable<People> findAll(Predicate predicate) {
return peopleRepository .findAll(predicate);
}
这样就可以查出所有了。