hibernate
Criteri e proiezioni
Ricerca…
Elenco utilizzando restrizioni
Supponendo di avere una tabella TravelReview con i nomi di città come colonna "titolo"
Criteria criteria =
session.createCriteria(TravelReview.class);
List review =
criteria.add(Restrictions.eq("title", "Mumbai")).list();
System.out.println("Using equals: " + review);
Possiamo aggiungere restrizioni ai criteri concatenandoli come segue:
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();
Utilizzando le proiezioni
Se vogliamo recuperare solo poche colonne, possiamo usare la classe Proiezioni per farlo. Ad esempio, il codice seguente recupera la colonna del titolo
// 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();
Usa filtri
@Filter
è usato come campo WHERE
, qui alcuni esempi
Entità studentesca
@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 */
}
Entità di studio
@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 */
}
In questo modo, ogni volta che il filtro "attivo" è abilitato,
-Ogni interrogazione che facciamo sull'entità studentesca restituirà TUTTI gli Studenti con SOLO il loro state = true
studi state = true
-Ogni interrogazione che facciamo sull'entità dello studio restituirà TUTTI state = true
studi sullo state = true
-Ogni interrogazione che facciamo sul StudentStudy entiy restituirà SOLO quelli con uno state = true
rapporto di studio
Si noti che study_id è il nome del campo sulla tabella sql StudentStudy