开发者

Is there any way to recover objects matching several criterias (not necessairly ID)?

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 a开发者_Go百科sked 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 parameter class having three attributes: name, type and value. Name will be name of you column, type will be equals, less then, greater then etc. condition types, and value will 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:

public <T extends Serializable> List<T> load(List<Parameter> params, Class<T> type)
{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        List<T> searchResult;
        session.beginTransaction(); 
        Criteria criteria = createCriteriaFromParams(params);    
        searchResult = criteria.list();  

        return searchResult;
}  

This is very simple scenario. You can create some complex criteria by adding some extra attributes in parameter list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜