oneToMany 关系中的 HQL 查询

我们有两个实体,Person并且House

一个Person可以有很多House

Person我正在尝试编写一个 HQL 查询,该查询获取按 列表大小排序的列表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);


慕田峪7331174
浏览 111回答 1
1回答

Helenr

我认为应该是public interface PersonRepository&nbsp; extends JpaRepository<Person, Long> {&nbsp; &nbsp; &nbsp; @Query(value = "select distinct p from Person p join p.houses h where h.value > 400 order by p.houses.size desc ")&nbsp; &nbsp; &nbsp; List<Person> getPersonWithMaxHouse();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java