Question

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.

Was it helpful?

Solution

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top