[英]JPA select Query to return Entity with @ManyToOne Mapping
I am a beginner, learning JPA, for practice I was working on this problem where I have two entity classes Person and Gym. 我是一名初学者,正在学习JPA,为了练习,我正在研究这个问题,我有两个实体类Person和Gym。
Person has : - id (auto-generated) - name - age - Gym (Many to One mapping) 人员具有:-id(自动生成)-姓名-年龄-健身房(多对一映射)
Gym has : - id (auto-generated) - name - rating - fee - List of Person (One to Many mapping) 健身房有:-ID(自动生成)-名称-评分-费用-人员列表(一对多映射)
Now, I have my PersonRepository which extends JpaRepository and have this following JPQL query where I am try to retrieve all persons with age < (some user input value) 现在,我有了扩展了JpaRepository的PersonRepository,并执行了以下JPQL查询,在该查询中我尝试检索所有年龄<(某些用户输入值)的人
The problem is the retrieved person list is always empty. 问题是检索到的人员列表始终为空。 I tried used fetch join but still it returns empty list. 我尝试使用提取联接,但仍返回空列表。
What should be the appropriate JPQL query for this scenario ? 对于这种情况,什么是合适的JPQL查询?
Thanks ! 谢谢 ! Balasubramanyam Balasubramanyam
Gym Entity 体育馆
@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
Person Entity 人实体
@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
PersonRepository 人员资料库
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);
}
In my service class this is what I am doing 在我的服务班里,这就是我在做什么
List<Person> filteredPersonList = personRepository.filterByAge(age);
System.out.println(filteredPersonList); // prints empty
If you change your repository to this you wont need to construct the query and will work. 如果将存储库更改为此,则无需构造查询即可使用。
public interface PersonRepository extends JpaRepository<Person, Integer>{
List<Person> findByAgeLessThanEqual(int age);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.