Java get query result

Java Query getResultList()

The method getResultList() from Query is declared as:

The method getResultList() returns a list of the results

The method getResultList() throws the following exceptions:

  • IllegalStateException — if called for a Java Persistence query language UPDATE or DELETE statement
  • QueryTimeoutException — if the query execution exceeds the query timeout value set and only the statement is rolled back
  • TransactionRequiredException — if a lock mode other than NONE has been set and there is no transaction or the persistence context has not been joined to the transaction
  • PersistenceException — if the query execution exceeds the query timeout value set and the transaction is rolled back
  • LockTimeoutException — if pessimistic locking fails and only the statement is rolled back
  • PessimisticLockException — if pessimistic locking fails and the transaction is rolled back

Example

The following code shows how to use Query from javax.persistence.

Specifically, the code shows you how to use Java Query getResultList()

import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; public class CountNoOFColumns < public static void main(String[] args) < EntityManagerFactory emf = Persistence.createEntityManagerFactory("perfcassandra"); EntityManager em = emf.createEntityManager(); Query q = em.createQuery("select u from UserDTO u"); q.setMaxResults(100000); q.getResultList(); System.out.println(q.getResultList().size()); > >
import java.util.*; import javax.persistence.*; public class SelectTest < public static void main(String[] args) < EntityManagerFactory f = Persistence.createEntityManagerFactory("emp"); EntityManager m = f.createEntityManager(); Query q = m.createQuery("select e from Emp e"); List list = q.getResultList(); Iterator itr = list.iterator(); System.out.println("following objects are fetched. "); while (itr.hasNext()) < Emp e = itr.next();// w w w . d e m o 2 s .c o m System.out.println(e.getId() + "\t" + e.getName() + "\t" + e.getJob() + "\t" + e.getSalary()); > m.close(); > >
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import com.durasoft.domain.User; public class ConsoleClient < public static void main(String[] args) < EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAServletLab"); EntityManager em = emf.createEntityManager(); Query query = em.createQuery("select u from User u where " + "u.userName=:p1 and u.password=:p2"); query.setParameter("p1", "sam23"); query.setParameter("p2", "abcde"); User u = (User) query.getResultList().get(0); System.out.println(u.getUserType().getDescription()); query = em.createQuery("select p from Person p " + "where p.user.id=:p1"); query.setParameter("p1", u.getId()); System.out.println(query.getResultList()); em.close();// w w w . d em o2 s . c o m > >

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Running JPA Queries

In addition, the Query interface defines a method for running DELETE and UPDATE queries:

This page covers the following topics:

Ordinary Query Execution (with getResultList)

The following query retrieves all the Country objects in the database. The query should be ran using the getResultList getResultList() TypedQuery’s method Execute a SELECT query and return the query results as a typed List. See JavaDoc Reference Page. method, as we expect to receive multiple objects in return:

TypedQueryjavax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page.  query = em.createQuerycreateQuery(qlString, resultClass)EntityManager's methodCreate an instance of TypedQuery for executing a Java Persistence query language statement.See JavaDoc Reference Page. ("SELECT c FROM Country c", Country.class); List results = query.getResultListgetResultList()TypedQuery's methodExecute a SELECT query and return the query results as a typed List.See JavaDoc Reference Page. ();
Queryjavax.persistence.QueryJPA interfaceInterface used to control query execution.See JavaDoc Reference Page.  query = em.createQuerycreateQuery(qlString)EntityManager's methodCreate an instance of Query for executing a Java Persistence query language statement.See JavaDoc Reference Page. ("SELECT c FROM Country c"); List results = query.getResultListgetResultList()Query's methodExecute a SELECT query and return the query results as an untyped List.See JavaDoc Reference Page. ();

An attempt to cast the above results to a parameterized type ( List ) will cause a compilation warning. If, however, the new TypedQuery javax.persistence.TypedQuery JPA interface Interface used to control the execution of typed queries. See JavaDoc Reference Page. interface is used — casting is unnecessary and the warning is avoided.

The query result collection functions as any other ordinary Java collection. For example, a result collection of a parameterized type can be iterated easily using an enhanced for loop:

for (Country c : results)  System.out.println(c.getName()); > 

Note that to only print the country names, a query using projection and retrieving country names directly instead of retrieving the entire Country instances would be more efficient.

Single Result Query Execution (with getSingleResult)

The getResultList getResultList() TypedQuery’s method Execute a SELECT query and return the query results as a typed List. See JavaDoc Reference Page. method (which was discussed above) can also be used to run queries that return a single result object. In this case, the result object has to be extracted from the result collection after query execution (e.g. by results.get(0) ). To eliminate this routine operation JPA provides an additional method, getSingleResult getSingleResult() TypedQuery’s method Execute a SELECT query that returns a single result. See JavaDoc Reference Page. , as a more convenient method when exactly one result object is expected.

The following aggregate query always returns a single result object, which is a Long object reflecting the number of Country objects in the database:

TypedQueryjavax.persistence.TypedQueryJPA interfaceInterface used to control the execution of typed queries.See JavaDoc Reference Page.  query = em.createQuerycreateQuery(qlString, resultClass)EntityManager's methodCreate an instance of TypedQuery for executing a Java Persistence query language statement.See JavaDoc Reference Page. ( "SELECT COUNT(c) FROM Country c", Long.class); long countryCount = query.getSingleResultgetSingleResult()TypedQuery's methodExecute a SELECT query that returns a single result.See JavaDoc Reference Page. (); 
Query query = em.createQuerycreateQuery(qlString)EntityManager's methodCreate an instance of Query for executing a Java Persistence query language statement.See JavaDoc Reference Page. ("SELECT COUNT(c) FROM Country c"); long countryCount = (Long)query.getSingleResultgetSingleResult()Query's methodExecute a SELECT query that returns a single untyped result.See JavaDoc Reference Page. (); 

An aggregate COUNT query always returns one result, by definition. In other cases our expectation for a single object result might fail, depending on the database content. For example, the following query is expected to return a single Country object:

Query query = em.createQuerycreateQuery(qlString)EntityManager's methodCreate an instance of Query for executing a Java Persistence query language statement.See JavaDoc Reference Page. ( "SELECT c FROM Country c WHERE c.name = 'Canada'"); Country c = (Country)query.getSingleResultgetSingleResult()Query's methodExecute a SELECT query that returns a single untyped result.See JavaDoc Reference Page. ();

DELETE and UPDATE Query Execution (with executeUpdate)

For example, the following query deletes all the Country instances:

int count = em.createQuerycreateQuery(qlString)EntityManager's methodCreate an instance of Query for executing a Java Persistence query language statement.See JavaDoc Reference Page. ("DELETE FROM Country").executeUpdateexecuteUpdate()Query's methodExecute an update or delete statement.See JavaDoc Reference Page. ();

The following query resets the area field in all the Country instances to zero:

int count = em.createQuerycreateQuery(qlString)EntityManager's methodCreate an instance of Query for executing a Java Persistence query language statement.See JavaDoc Reference Page. ("UPDATE Country SET area = 0").executeUpdateexecuteUpdate()Query's methodExecute an update or delete statement.See JavaDoc Reference Page. ();

On success — the executeUpdate method returns the number of objects that have been updated or deleted by the query.

The Query Structure section explains DELETE and UPDATE queries in more detail.

Which JPA is Faster?

Copyright © 2003, 2010, 2023 ObjectDB Software, all rights reserved. The JPA API Reference Documentation (JavaDoc) on this website is derived with some adjustments from the open source JPA 2 RI (EclipseLink) and is available under the terms of the Eclipse Public License, v. 1.0 and Eclipse Distribution License, v. 1.0. The JDO API Reference Documentation (JavaDoc) on this website is derived with some adjustments from the JDO 2.2 API and is available under the terms of the Apache License, v. 2.0. Images on this website are available under these licecnes. Documentation on this website explains how to use JPA in the context of the ObjectDB Object Database but mostly relevant also for ORM JPA implementations, such as Hibernate (and HQL), EclipseLink, TopLink, OpenJPA and DataNucleus. ObjectDB is not an ORM JPA implementation but an Object Database (ODBMS) for Java with built in JPA 2 support.

Источник

Читайте также:  METANIT.COM
Оцените статью