Java – hibernate and criteria APIs return an object array instead of tuple

I'm trying the criteria API and I'm facing strange problems with tuples

I am building a query similar to that described here: https://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html_single/#querycriteria -tuple

But for some reason, the result list is actually list < object [] > instead of list < tuple >, so my code failed at run time I can easily solve the problem and change the iteration on the list so that it works at runtime, but I want to know what I did wrong here

This is the code of my query:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();

Root<Users> usersRoot = cq.from(Users.class);
Path<String> namePath = usersRoot.get(Users_.fullName);
Path<Integer> employeeIdPath = usersRoot.get(Users_.employeeId);
cq.multiselect(namePath,employeeIdPath);

List<Tuple> resultList = entityManager.createQuery(cq).getResultList();

List<String> names = new ArrayList<>();
for (Tuple tuple : resultList) {
    names.add(tuple.get(namePath));
}

This code compiles correctly, but when I reach the for loop, I get a ClassCastException: Java Lang. ClassCastException: [ljava. Lang. object; cannot be converted to javax.persistence.tuple

Debugging confirms that the returned result list does contain object [] instead of tuple, thus breaking the API contract

My hibernate Maven dependencies:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.2.21.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-jpamodelgen</artifactId>
    <version>5.0.4.Final</version>
</dependency>

This code is deployed as an EJB 3.1 application to Weblogic 12.1 3 container, the underlying database is Oracle 12

Solution

I've tried your example and it works well View this test in my GitHub Repository:

doInJPA(entityManager -> {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = cb.createTupleQuery();

    Root<BlogEntityProvider.Post> postRoot = cq.from(BlogEntityProvider.Post.class);
    Path<Long> idPath = postRoot.get("id");
    Path<String> titlePath = postRoot.get("title");
    cq.multiselect(idPath,titlePath);

    List<Tuple> resultList = entityManager.createQuery(cq).getResultList();

    for (Tuple tuple : resultList) {
        Long id = tuple.get(idPath);
        String title = tuple.get(titlePath);
    }
});

This is 5.0 3.Final. If this does not apply to 4.2 21. Please add a question on Hibernate JIRA

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>