有什么区别:
Root<Person> person = cq.from(Person.class);
和
EntityType<Person> Person_ = em.getMetamodel().entity(Person.class);
Root<Person> person = cq.from(Person_);
我在几个教程中都见过。
最佳答案
分析
查看 Hibernate 的 CriteriaQuery parent's 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 只是一个接口(interface),而 EclipseLink 或 Hibernate 等实现提供者提供了实际的实现。下次如果你能考虑到这一点就太好了。
关于java - JPA2 Criteria API : What is the difference between using Entity. 类和 from 子句中元模型的 EntityType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10617467/