【问题标题】:Hibernate Criteria Collection of ObjectsHibernate Criteria 对象集合
【发布时间】:2011-10-21 16:15:31
【问题描述】:

我有一个包含对象集合的类。 例如:

class XmlRequest{
            Long id;
             List<PersonNmDTO> persons;
     }

class PersonNmDTO{
    String firstName;
    String lastName;
}

我想生成如下 SQL: select * from table where (firstname='xxxx' and lastname='yyyy') or (firstname='aaaa' and lastname='bbbb') or (firstname='pppp' and lastname='qqqq') .... ...

如何使用 Hibernate Criteria 生成此类 SQL?

【问题讨论】:

    标签: hibernate orm


    【解决方案1】:

    这是非常基本的用法。你读过the documentation吗?

    Criteria c = session.createCriteria(Person.class, "person");
    Disjunction or = Restrictions.disjunction();
    or.add(Restrictions.and(Restrictions.eq("person.firstName", "xxxx"),
                            Restrictions.eq("person.lastName", "yyyy")));
    or.add(Restrictions.and(Restrictions.eq("person.firstName", "aaaa"),
                            Restrictions.eq("person.lastName", "bbbb")));
    
    // ...
    criteria.add(or);
    List<Person> result = (List<Person>) c.list();
    

    请注意,DTO 应该表示“数据传输对象”,即在不传输持久实体的情况下传输数据的意思。所以将你的持久实体命名为PersonNmDTO 确实值得怀疑。

    【讨论】:

    • 析取或= Restrictions.disjunction();
    • 如果姓氏或名字为空或空字符串会怎样?
    • 查询不会找到该行,因为它不满足条件。 NULL != xxxx。
    猜你喜欢
    • 1970-01-01
    • 2011-08-31
    • 2015-08-29
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    相关资源
    最近更新 更多