0

有什么区别:

Root<Person> person = cq.from(Person.class);

EntityType<Person> Person_ = em.getMetamodel().entity(Person.class);
Root<Person> person = cq.from(Person_);

我在几个教程中都看到过..

4

1 回答 1

2

分析

查看 Hibernate 的CriteriaQuery 父级的 QueryStructure from(..)方法:

public <X> Root<X> from(Class<X> entityClass) {
    EntityType<X> entityType = criteriaBuilder.getEntityManagerFactory()
            .getMetamodel()
            .entity( entityClass );
    if ( entityType == null ) {
        throw new IllegalArgumentException( entityClass + " is not an entity" );
    }
    return from( entityType );
}

public <X> Root<X> from(EntityType<X> entityType) {
    RootImpl<X> root = new RootImpl<X>( criteriaBuilder, entityType );
    roots.add( root );
    return root;
}

我们看到,其中一个只是重载。

结果

更方便和样板转义的方法是将 Class 作为参数传递。

建议

您没有提供您正在使用的 JPA 实现,因为 JPA 的 CriteriaQuery 只是一个接口,而 EclipseLink 或 Hibernate 等实现提供者提供了实际实现。下次如果你考虑到这一点会更好。

于 2012-05-24T12:47:58.630 回答