【发布时间】:2019-09-01 14:39:24
【问题描述】:
我们有两个实体,Person 和 House。
一个Person 可以有多个House。
我正在尝试编写一个 HQL 查询,以获取按House 列表大小排序的Person 列表,其中一个条件是House 的值应大于@987654329 @。
我的班级人
@Entity
public class Person{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy =
"person", fetch = FetchType.LAZY)
private List<House> houses = new ArrayList<>();
/**
* utility method to adjust relation
* @param house
*/
public void addHouse( House house ) {
this.houses.add(house);
house.setPerson(this);
}
//constructors, getters and setter omitted..
}
我的班级之家
@Entity
public class House {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Integer value;
@ManyToOne
@JoinColumn(name = "person_id")
private Person person;
//constructors, getters and setters omitted..
}
我在数据库层上的表表示
Person House
id name id value person_id
1 George 1 500 1
2 Frederic 2 250 2
3 Jamal 3 500 3
4 600 3
我的查询结果应该是 [Jamal, George],不应该包括 Frederic,因为他唯一拥有的房子没有值 >400。
我的查询
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(value = "select p from Person p order by p.houses.size desc ")
List<Person> getPersonWithMaxHouse();
}
这样,我得到了一个根据房屋数量排序的人员列表。
如何添加House的值的条件。
我的第二个问题是关于我正在寻找的 hql 的 Sprig Data JPA Query 等效项?
例如,此存储库查询返回名称等于给定字符串的所有人员:List<Person> findAllByName(String Name);
【问题讨论】:
-
关于你的第二个问题 - JPA 是一个规范,我们可以在 ORM 行 Hibernate 中使用它们的特性,尝试使用链接然后你就会明白what-when-how.com/hibernate/…
-
我的第二个问题是关于使用 Spring Repositories 查询,例如: List
findAllByName(String Name);
标签: java hibernate spring-data-jpa jpql