gpt4 book ai didi

java - JPA 选择查询返回带有 @ManyToOne 映射的实体

转载 作者:行者123 更新时间:2023-12-02 01:36:36 25 4
gpt4 key购买 nike

我是一名初学者,正在学习 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

人员存储库

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);

}

关于java - JPA 选择查询返回带有 @ManyToOne 映射的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57514920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com