1

I have 3 tables, each mapped to an entity. The entities are something like this:

@Entity
@Table(name = "person")
public class Person implements Serializable {
    private int id;
    //other fields
}

@Entity
@Table(name = "phone")
public class Phone implements Serializable {
    private int id;
    private Long price;

    @ManyToOne
    @JoinColumn(name = "personId")
    private Person person;

    @ManyToOne
    @JoinColumn(name = "manufacturerId")
    private Manufacturer manufacturer;
    //other fields
}

@Entity
@Table(name = "manufacturer")
public class Manufacturer implements Serializable {
    private int id;
    private String name;
    //other fields
}

What I want to do is to create a method that will return a list of Persons that have phones from a specified manufacturer with the price in a specified range.

EDIT: My dao class implements EntityJpaDao . I would need a solution that would work with this implementation.

Sbiera Bogdan
  • 346
  • 1
  • 11
  • You want solution in SQL? HQL? Criteria? Here is an example similar to your problem http://stackoverflow.com/questions/4483576/jpa-2-0-criteria-api-subqueries-in-expressions – paulek Aug 30 '13 at 12:41
  • i'm new to persistency in java so,basically, i wan't a solution that works :).i'm not sure which one is better or applicable in my case. – Sbiera Bogdan Aug 30 '13 at 12:49

1 Answers1

1

Following query will return the Samsung mobile users with phone price range.

  Criteria criteria = session.createCriteria(Phone.class, "phone"); 
  criteria.createAlias("phone.person", "person")
  criteria.add(Restrictions.between("phone.price", minPrice, maxPrice));
  criteria.createAlias("phone.manufacturer","manufacturer");
  criteria.add(Restrictions.eq("manufacturer.name", Samsung)); 
  criteria.setProjection(Projections.property("person"));

  List<Person> persons = criteria.list();
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
  • i'm using JPA and entityManager. is there a way to call getSession() whit this implementation? – Sbiera Bogdan Aug 30 '13 at 12:51
  • entityManager doesn't have a createCriteria method, but i found that i could get the hibernate session from the entityManager using entityManager.unwrap(Session.class). It's almost perfect, except that my Person doesn't hold a reference to the phone, only the phone holds reference to the person. – Sbiera Bogdan Aug 30 '13 at 13:18