【发布时间】:2019-12-22 04:55:00
【问题描述】:
我是一名初学者,正在学习 JPA,为了练习我正在解决这个问题,我有两个实体类 Person 和 Gym。
人有: - id(自动生成) - 姓名 - 年龄 - 健身房(多对一映射)
健身房有: - id(自动生成) - 姓名 - 评分 - 费用 - 人员列表(一对多映射)
现在,我有我的 PersonRepository,它扩展了 JpaRepository 并有以下 JPQL 查询,我试图检索所有年龄
问题是检索到的人员列表始终为空。我尝试使用 fetch join 但它仍然返回空列表。
对于这种情况,合适的 JPQL 查询应该是什么?
谢谢!巴拉苏布拉曼亚姆
健身房实体
@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
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);
}
在我的服务类中,这就是我正在做的事情
List<Person> filteredPersonList = personRepository.filterByAge(age);
System.out.println(filteredPersonList); // prints empty
【问题讨论】:
-
应该是
left join fetch(或者如果你不想去健身房,你可以简单地删除该子句)。但无论如何,如果列表是空的,最可能的原因是,在很大程度上,使用 hy Hibernate 的数据库中没有这样的人。 -
您好!感谢您的快速回复。数据库中的person表和gym表确实有条目,我已经检查过了。我也检查了连接,我可以从我的应用程序中插入值。
-
然后尝试调试以找出发生了什么。启用 SQL 日志记录以了解正在执行的查询。调用 findAll() 并打印它返回的内容,以查看实际存在的人。
标签: java hibernate spring-boot jpa jpql