how to query an embedded entity by using a query builder

Posted by user577719 on Stack Overflow See other posts from Stack Overflow or by user577719
Published on 2011-01-16T19:30:28Z Indexed on 2011/01/16 19:53 UTC
Read the original article Hit count: 198

Filed under:
|
|

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...

© Stack Overflow or respective owner

Related posts about java

Related posts about eclipselink