Reputation: 1906
We have two Entities, Person
and House
.
One Person
can have Many House
.
I'm trying to write an HQL query that get the list of Person
ordered by the size of the list of House
, with one condition, that the value of the House
should be greater than 400
.
My class Person
@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..
}
My class House
@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..
}
My tables representation on the database Layer
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
The result of my query should be [Jamal, George], and Frederic should not be included because the only house he has, doesn't have a value >400
.
My query
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(value = "select p from Person p order by p.houses.size desc ")
List<Person> getPersonWithMaxHouse();
}
with that, I'm getting an ordered list of persons based on the number of houses.
How could I add the condition of the value of the House
.
My second question is about the Sprig Data JPA Query equivalent of the hql I'm looking?
For example this repository query return all the persons whose names is equal to the given String : List<Person> findAllByName(String Name);
Upvotes: 1
Views: 802
Reputation: 1180
I think it should be
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();
}
Upvotes: 2