在hibernate中,我们可以在条件中包含标准

时间:2015-06-18 15:09:12

标签: hibernate criteria

假设我已经在课程上创建了一个标准。现在我希望从我将在当前标准中使用的不同表中获取数据。为此,我必须在新表上创建标准。那么是否可以在标准内创建新标准?

1 个答案:

答案 0 :(得分:1)

Yes  It is possible  , see the description below from the hibernate documentation

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

15.4。协会

通过使用createCriteria()导航关联,您可以在相关实体上指定约束:

List cats = sess.createCriteria(Cat.class)
    .add( Restrictions.like("name", "F%") )
    .createCriteria("kittens")
        .add( Restrictions.like("name", "F%") )
    .list();

第二个createCriteria()返回一个新的Criteria实例,它引用了kittens集合的元素。

还有一种在某些情况下有用的替代形式:

List cats = sess.createCriteria(Cat.class)
    .createAlias("kittens", "kt")
    .createAlias("mate", "mt")
    .add( Restrictions.eqProperty("kt.name", "mt.name") )
    .list();
(createAlias() does not create a new instance of Criteria.)

The kittens collections held by the Cat instances returned by the previous two queries are not pre-filtered by the criteria. If you want to retrieve just the kittens that match the criteria, you must use a ResultTransformer.

List cats = sess.createCriteria(Cat.class)
    .createCriteria("kittens", "kt")
        .add( Restrictions.eq("name", "F%") )
    .setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP)
    .list();
Iterator iter = cats.iterator();
while ( iter.hasNext() ) {
    Map map = (Map) iter.next();
    Cat cat = (Cat) map.get(Criteria.ROOT_ALIAS);
    Cat kitten = (Cat) map.get("kt");
}