I am working on a project that is using hibernate.
We have a database and now I would like to query it.
In the ideal case, I know I am able to recover an object by its ID or by using Hibernate’s query language. But it would be optimal to me if there was a method to which I send an object with the attributes I want to be used as a filter and get back all the objects in that table that match these criterias.
For instance
Person p = new Person();
p.setName("Junior");
p.setAge(10);
session.Load(Person.class, p); //this would return all "junior" with age = 10
I imagine Hibernate would provide a similar functionality. Does it? Which method should I use?
Thanks,
Oscar
EDIT:
@nIKUNJ indicated me to Criteria, which would be something very similar to what I need.
The problem is: I would like to have a DatabaseManager class, which would handle the save, load, etc features.
For instance, my load would look like this:
public <T extends Serializable> List<T> load(T filters, Class<T> type)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
List<T> searchResult;
session.beginTransaction();
searchResult = ((List<T>)session.get(type, filters)); //assuming the method
//I asked for in the question exists
return searchResult;
}
This way, I would be able to send almost any object to this method and the method would query the database and return me a List of objects that match the criteria.
Do you have any idea how I could mimic this behavior that using the Criteria class?
Thanks,
Oscar
I think Hibernate Criteria can help you.
You can use one
parameterclass having three attributes:name, type and value.Namewill be name of you column,typewill be equals, less then, greater then etc. condition types, andvaluewill be value for that condition.For example,
name="person.age", type = greater equal, value=18. Create a utility method that converts these parameters into criteria objects.Now, create a method like this:
This is very simple scenario. You can create some complex criteria by adding some extra attributes in parameter list.