我们有两个实体,Person
和House
。
一个Person
可以有很多House
。
我正在尝试编写一个 HQL 查询,它获取按 的列表Person
大小排序的列表House
,在一个条件下, 的值House
应该大于400
。
我的班级人物
@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,因为他拥有的唯一房子没有 value >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 查询?
例如,此存储库查询返回名称等于给定 String 的所有人员: List<Person> findAllByName(String Name);
我认为应该是
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(value = "select distinct p from Person p join p.houses h where h.value > 400 order by p.houses.size desc ")
List<Person> getPersonWithMaxHouse();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句