开发者

Hibernate: Looking for a way to simplify how I search for objects using an object

I'm using Hibernate Core 3.3.4.GA. I'm looking for a way to simplify my code (if possible). Right now, I want to search for objects of type "MyObj" using an instance of MyObj, which will be partially populated. So I have …

// inputObj is a partially populated object of type MyObj
Criteria crit = session.createCriteria(MyObj.class);
if (inputObj.getField1() != null) { 
    crit.add( Restrictions.eq( "field1", inputObj.getField1() );
}
if (inputObj.getField2() != null) { 
    crit.add( Restrictions.eq( "field2", inputObj.getField2() );
}
…
List obj开发者_开发技巧ects = crit.list();

Problem is, there is more than 20 fields, so the code is onerous. Is there a way to simplify the above?

Thanks, - Dave


Use org.hibernate.criterion.Example to get the behavior you're describing:

    List results = session.createCriteria(MyObj.class)
        .add( Example.create(inputObj) )
        .list();

This is described in section 15.4 of the Reference Documentation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜