Reputation: 5952
I will explain the problem with an example.
I have a Vehicle object which has a model name and a make. When the make is given, relevant vehicle should be listed. when both make and model is given,then suitable vehicles should be listed.
For example:
There is an entity called 'Vehicle' .It has a proxy called makeModel whose Entity name is MakeModel
. MakeModel has proxies which are 'make' and 'model' whose entity names are Model and Make.Both Entititiyes 'Model' and 'Make' have String variable 'name'.Here are classes
class Vehicle{
private Integer vehicleId;
private MakeModel makeMOdel;
//getters and setters
}
class MakeModel {
private Make make;
private Model model;
//getters and setters
}
class Make{
private Integer mid;
private String make;
}
class Model{
private Integer mdlid;
private String modelName;
}
Here is how I tried to get vehicle list. Here, session
is Hibernate Session.
Criteria cr= session.createCriteria(Vehicle.class);
MakeModel mkmd=new MakeModel();
if( /* if only the make is give */){
Make mk=new Make();
mk.setMake("Toyota");
mkmd.setMake(mk);
}
else if(if both make and and model given){
Make mk=new Make();
mk.setMake("Toyota");
mkmd.setMake(mk);
Model md=new Model("Venus");
mkmd.setModel(md);
}
cr.createCriteria("makeModel").add(Example.create(mkmd));List l=cr.list();
But this returns all vehicles. I want to get all vehicles using hibernate criteria not HQL.
A same question can be found here and referred this also. Any one let me know where is wrong and how to retrieve vehicle list according to given criteria.
Upvotes: 0
Views: 432
Reputation: 10270
Supposing that you are passing to your function makeValue and modelValue, which are the make and the model you want, you would have:
Criteria cr = session.createCriteria(Vehicle.class); // Create the criteria on desired class
cr.createAlis("makeModel", "makeModel")
.createAlias("makeModel.make", "make")
.createAlias("makeModel.model", "model"); // Creating aliases makes a join on those tables
if (makeValue != null){
cr.add(Restrictions.eq("make.make", makeValue)) // If you have a makeValue passed, filter by it
}
if (makeModel != null){
cr.add(Restrictions.eq("model.modelName", modelValue)); // If you have a makeModel passed, filter by it
}
return cr.list(); // Return the list
The result will be a List<Vehicle>
. You can add a @SuppressWarnings("unchecked")
to your method to avoid seeing unchecked cast warnings.
Upvotes: 2