简体   繁体   中英

Unable to select a column from an Oracle View using JPA 2 Criteria API

I have an existing working query that selects a column from an entity mapped to an Oracle View using the following JPQL

    SELECT COUNT(o.id) FROM MyEntityView o

I refactored it to use the JPA 2 Criteria API with the following code:

    MyEntityView model = new MyEntityView();
    CriteriaBuilder criteriaBuilder = model.entityManager().getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
    Root<MyEntityView > theView = criteriaQuery.from(MyEntityView.class);

    criteriaQuery.select(criteriaBuilder.count(theView.get(MyEntityView_.id))); // ERROR!
    TypedQuery<Long> query = model.entityManager().createQuery(criteriaQuery);
    ....

But it generates the following error on creating the select statement:

    java.lang.NullPointerException
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:110)
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:218)
    at org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:189) 
    at com.mycomp.domain.view.MyEntityViewIntegrationTest.testMarkerMethod(MyEntityViewIntegrationTest.java:35)

I tried changing the mapping to a table instead of a view and the it does work properly.

Is this a Hibernate Bug or am I missing something?

This sounds like a bug (similar to the problem reported in JPA 2 CriteriaQuery Using ID columns throws Null Pointer EX ) and I couldn't find an existing Jira issue for it and suggest creating a new one.

That being said, I don't really see the point of using a CriteriaQuery here, especially if you don't use the static metamodel for full type-safety. It's maybe a simplified example though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM