[英]JPA select Query to return Entity with @ManyToOne Mapping
我是一名初學者,正在學習JPA,為了練習,我正在研究這個問題,我有兩個實體類Person和Gym。
人員具有:-id(自動生成)-姓名-年齡-健身房(多對一映射)
健身房有:-ID(自動生成)-名稱-評分-費用-人員列表(一對多映射)
現在,我有了擴展了JpaRepository的PersonRepository,並執行了以下JPQL查詢,在該查詢中我嘗試檢索所有年齡<(某些用戶輸入值)的人
問題是檢索到的人員列表始終為空。 我嘗試使用提取聯接,但仍返回空列表。
對於這種情況,什么是合適的JPQL查詢?
謝謝 ! Balasubramanyam
體育館
@Entity
public class Gym {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int gym_id;
@NotNull
private String name;
@NotNull
private String city;
@NotNull
@Max(5)
private double rating;
@NotNull
private double fee;
@OneToMany(mappedBy="gym",
cascade= {CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH}, fetch=FetchType.EAGER)
@JsonManagedReference
private List<Person> personList;
public Gym() {
super();
}
public Gym(int gym_id, @NotNull String name, @NotNull double rating, @NotNull double fee, List<Person> personList,
@NotNull String city) {
super();
this.gym_id = gym_id;
this.name = name;
this.rating = rating;
this.fee = fee;
this.personList = personList;
this.city = city;
}
// getters and setters
人實體
@Entity
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@NotNull
private String name;
@NotNull
private int age;
@ManyToOne (cascade={CascadeType.MERGE, CascadeType.PERSIST,
CascadeType.REFRESH, CascadeType.DETACH})
@JoinColumn
@JsonBackReference
private Gym gym;
public Person() {
super();
}
public Person(int id, @NotNull String name, @NotNull int age, Gym gym) {
super();
this.id = id;
this.name = name;
this.age = age;
this.gym = gym;
}
// getters and setters
人員資料庫
public interface PersonRepository extends JpaRepository<Person, Integer>{
@Query("select p from Person p join fetch p.gym where p.age<=(:age)")
List<Person> filterByAge(@Param("age") int age);
}
在我的服務班里,這就是我在做什么
List<Person> filteredPersonList = personRepository.filterByAge(age);
System.out.println(filteredPersonList); // prints empty
如果將存儲庫更改為此,則無需構造查詢即可使用。
public interface PersonRepository extends JpaRepository<Person, Integer>{
List<Person> findByAgeLessThanEqual(int age);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.