@NamedEntityGraph的使用时为了解决sql查询过多的问题
@Entity
@Table(name="s_person")
@NamedEntityGraph(name="person.all",attributeNodes={@NamedAttributeNode("address"),@NamedAttributeNode("cards")})
public class Person {
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Id
private String id;
private String username;
private String age;
@OneToOne
@JoinColumn(name="address_id",referencedColumnName="id")
private Address address;
@OneToMany(fetch=FetchType.EAGER)
@JoinTable(name="s_person_card",joinColumns={@JoinColumn(name="p_id")}
,inverseJoinColumns={@JoinColumn(name="c_id")})
private List<Cards> cards;
public List<Cards> getCards() {
return cards;
}
public void setCards(List<Cards> cards) {
this.cards = cards;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
接口
public interface PersonRepository extends JpaRepository<Person, String>{
@EntityGraph(value = "person.all" , type=EntityGraphType.FETCH)
Person findById(String id);
}
当去查询person的时候会自动查询Adress和Cards里面的内容,且只发出一条sql语句,这样就解决了是使用关联查询导致sql查询过多的问题