Poniżej zamieściłem kod trzech odpowiednio zmapowanych klas. Żeby pobrać wszystkich ludzi z tabeli Ludzie, robie to za pomocą funkcji:
public List<Ludzie> getLudzie() {
Session session = factory.openSession();
List<Ludzie> ludzieList = session.createQuery("from Ludzie").list();
session.close();
return ludzieList;
}
Chcę zrobić teraz tak żeby nie pobierała wszystkich rekordów z tabeli Ludzie, a jedynie tych którzy są powiązani z produktami które mają atrybut idt=1. Jak to zrobić?
@Entity
@Table(name="ludzie")
public class Ludzie {
private int idl;
private String nazwa;
private Set<Ludzie_Produkty> ludzie_produkty = new HashSet<Ludzie_Produkty>();
@Id
@GeneratedValue
public int getIdl() { return this.idl; }
public void setIdl(int idl) { this.idl=idl; }
@Column(name="nazwa")
public String getNazwa() { return this.nazwa; }
public void setNazwa(String nazwa) { this.nazwa=nazwa; }
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "ludzie")
public Set<Ludzie_Produkty> getLudzie_produkty() {
return ludzie_produkty;
}
public void setLudzie_produkty(Set<Ludzie_Produkty> ludzie_produkty) {
this.ludzie_produkty = ludzie_produkty;
}
}
@Entity
@Table(name="produkty")
public class Produkty {
private int idp;
private int idt;
private String nazwa;
private double cena;
private int liczba;
private Set<Ludzie_Produkty> ludzie_produkty = new HashSet<Ludzie_Produkty>();
@Id
@GeneratedValue
public int getIdp() {
return idp;
}
public void setIdp(int idp) {
this.idp = idp;
}
public int getIdt() {
return idt;
}
public void setIdt(int idt) {
this.idt = idt;
}
public String getNazwa() {
return nazwa;
}
public void setNazwa(String nazwa) {
this.nazwa = nazwa;
}
public double getCena() {
return cena;
}
public void setCena(double cena) {
this.cena = cena;
}
public int getLiczba() {
return liczba;
}
public void setLiczba(int liczba) {
this.liczba = liczba;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "produkty")
public Set<Ludzie_Produkty> getLudzie_produkty() {
return ludzie_produkty;
}
public void setLudzie_produkty(Set<Ludzie_Produkty> ludzie_produkty) {
this.ludzie_produkty = ludzie_produkty;
}
}
@Entity
@Table(name="ludzie_produkty")
public class Ludzie_Produkty {
private int idlp;
private int idl;
private int idp;
private int liczba;
private Ludzie ludzie;
private Produkty produkty;
@Id
@GeneratedValue
public int getIdlp() {
return idlp;
}
public void setIdlp(int idlp) {
this.idlp = idlp;
}
public int getLiczba() {
return liczba;
}
public void setLiczba(int liczba) {
this.liczba = liczba;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="idl", nullable=false)
public Ludzie getLudzie() {
return ludzie;
}
public void setLudzie(Ludzie ludzie) {
this.ludzie = ludzie;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="idp", nullable=false)
public Produkty getProdukty() {
return produkty;
}
public void setProdukty(Produkty produkty) {
this.produkty = produkty;
}
}