hibernate
Kryteria i prognozy
Szukaj…
Lista przy użyciu ograniczeń
Zakładając, że mamy tabelę TravelReview z nazwami miast w kolumnie „tytuł”
Criteria criteria =
session.createCriteria(TravelReview.class);
List review =
criteria.add(Restrictions.eq("title", "Mumbai")).list();
System.out.println("Using equals: " + review);
Możemy dodać ograniczenia do kryteriów, łącząc je w następujący sposób:
List reviews = session.createCriteria(TravelReview.class)
.add(Restrictions.eq("author", "John Jones"))
.add(Restrictions.between("date",fromDate,toDate))
.add(Restrictions.ne("title","New York")).list();
Korzystanie z projekcji
Jeśli chcemy pobrać tylko kilka kolumn, możemy to zrobić za pomocą klasy Projections. Na przykład poniższy kod pobiera kolumnę tytułu
// Selecting all title columns
List review = session.createCriteria(TravelReview.class)
.setProjection(Projections.property("title"))
.list();
// Getting row count
review = session.createCriteria(TravelReview.class)
.setProjection(Projections.rowCount())
.list();
// Fetching number of titles
review = session.createCriteria(TravelReview.class)
.setProjection(Projections.count("title"))
.list();
Użyj filtrów
@Filter
jest używany jako obóz WHERE
, tutaj kilka przykładów
Podmiot studencki
@Entity
@Table(name = "Student")
public class Student
{
/*...*/
@OneToMany
@Filter(name = "active", condition = "EXISTS(SELECT * FROM Study s WHERE state = true and s.id = study_id)")
Set<StudentStudy> studies;
/* getters and setters methods */
}
Podmiot badający
@Entity
@Table(name = "Study")
@FilterDef(name = "active")
@Filter(name = "active", condition="state = true")
public class Study
{
/*...*/
@OneToMany
Set<StudentStudy> students;
@Field
boolean state;
/* getters and setters methods */
}
StudentStudy Entity
@Entity
@Table(name = "StudentStudy")
@Filter(name = "active", condition = "EXISTS(SELECT * FROM Study s WHERE state = true and s.id = study_id)")
public class StudentStudy
{
/*...*/
@ManytoOne
Student student;
@ManytoOne
Study study;
/* getters and setters methods */
}
W ten sposób za każdym razem, gdy filtr „aktywny” jest włączony,
-Każde zapytanie, które wykonujemy na jednostce studenckiej, zwróci WSZYSTKICH Studentów, których TYLKO ich state = true
badania
-Każde zapytanie, które wykonujemy na obiekcie Study, zwróci WSZYSTKIE state = true
badania
-Każde zapytanie, które wykonamy na jednostce StudentStudy, zwróci TYLKO te z relacją state = true
Badanie
Proszę zauważyć, że study_id to nazwa pola w tabeli StudentStudy sql