how to query an embedded entity by using a query builder
- by user577719
I've searched quite a time for an answer to this question. Following Codesmell:
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Integer id;
@Column(nullable = true, length = 50)
@Size(max = 50)
private String name;
@Embedded
@Valid
protected Adress adress;
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public void getName() {
return this.name;
}
public void setAdress(Adress adress) {
this.adress = adress;
}
public void getAdress() {
return this.adress;
}
}
@Embeddable
public class Adress {
@Column(nullable = false, length = 50)
@Size(max = 50)
@NotNull
private String place;
public void setPlace(String place) {
this.place = place;
}
public void getPlace() {
return this.place;
}
}
public class PersonDaoJpa {
public List<Ort> findByPerson(final Person person) {
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Person> query = builder.createQuery(Person.class);
Root<Person> rootPerson = query.from(Person.class);
List<Predicate> wherePredicates = new ArrayList<Predicate>();
if (person.getName() != null) {
wherePredicates.add( builder.like(builder.lower(rootPerson.<String>get("name")), ort.getName().toLowerCase()) );
}
Adresse adresse = ort.getAdresse();
if (adresse != null) {
if(adresse.getPlace() != null) {
// this won't work
wherePredicates.add( builder.like(builder.lower(rootPerson.<String>get("person.adress.place")), adresse.getPlace().toLowerCase()) );
}
}
Predicate whereClause = builder.and(wherePredicates.toArray(new Predicate[0]));
query.where(whereClause);
return this.entityManager.createQuery(query).getResultList();
}
}
How can I access the Adress.place through rootPerson? rootPerson.get("place"), or rootPerson.get("adress.place") won't work...