我已经搜索了很长时间来回答这个问题。以下代码:
@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();
}
}
如何通过rootPerson访问Adress.place? rootPerson.get(“place”)或rootPerson.get(“adress.place”)将无效...
答案 0 :(得分:2)
我认为这可行:
wherePredicates.add( builder.like(builder.lower(rootPerson.<String>get("adress").get("place")), adresse.getPlace().toLowerCase()) );