List of usage examples for javax.persistence TypedQuery getSingleResult
X getSingleResult();
From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java
private DatafileMetadata fetchMetadata(File file) { EntityManager entityManager = createEntityManager(); try {/*from w w w .j a v a 2 s . co m*/ TypedQuery<DatafileMetadata> query = entityManager.createQuery( "from DatafileMetadata d where d.capturedFilePathname = :pathName", DatafileMetadata.class); query.setParameter("pathName", file.getAbsolutePath()); return query.getSingleResult(); } catch (NoResultException ex) { return null; } finally { entityManager.close(); } }
From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirResourceDao.java
@Override public BaseHasResource readEntity(IIdType theId, boolean theCheckForForcedId) { validateResourceTypeAndThrowIllegalArgumentException(theId); Long pid = translateForcedIdToPid(getResourceName(), theId.getIdPart()); BaseHasResource entity = myEntityManager.find(ResourceTable.class, pid); if (entity == null) { throw new ResourceNotFoundException(theId); }/* ww w . j av a 2s . c o m*/ if (theId.hasVersionIdPart()) { if (theId.isVersionIdPartValidLong() == false) { throw new ResourceNotFoundException( getContext().getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "invalidVersion", theId.getVersionIdPart(), theId.toUnqualifiedVersionless())); } if (entity.getVersion() != theId.getVersionIdPartAsLong().longValue()) { entity = null; } } if (entity == null) { if (theId.hasVersionIdPart()) { TypedQuery<ResourceHistoryTable> q = myEntityManager.createQuery( "SELECT t from ResourceHistoryTable t WHERE t.myResourceId = :RID AND t.myResourceType = :RTYP AND t.myResourceVersion = :RVER", ResourceHistoryTable.class); q.setParameter("RID", pid); q.setParameter("RTYP", myResourceName); q.setParameter("RVER", theId.getVersionIdPartAsLong()); try { entity = q.getSingleResult(); } catch (NoResultException e) { throw new ResourceNotFoundException( getContext().getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "invalidVersion", theId.getVersionIdPart(), theId.toUnqualifiedVersionless())); } } } validateResourceType(entity); if (theCheckForForcedId) { validateGivenIdIsAppropriateToRetrieveResource(theId, entity); } return entity; }
From source file:net.navasoft.madcoin.backend.model.controller.impl.WorkRequestDataAccess.java
/** * Gets the by logical id.//from w ww. j av a 2 s . co m * * @param idEntity * the id entity * @return the by logical id * @since 2/09/2014, 09:31:40 PM */ @Override public WorkRequests getByLogicalId(Serializable idEntity) { if (idEntity instanceof WorkRequestsPK) { if (((WorkRequestsPK) idEntity).getIdWorkRequests() != 0) { TypedQuery<WorkRequests> query = entityManager.createNamedQuery( "WorkRequests." + CompleteNormalizedEntity.COMPLETE_QUERY_ID, WorkRequests.class); query.setParameter("categoryId", ((WorkRequestsPK) idEntity).getCategoryId()); query.setParameter("orderId", ((WorkRequestsPK) idEntity).getIdWorkRequests()); List<WorkRequests> x = query.getResultList(); return x.get(0); } else { TypedQuery<WorkRequests> query = entityManager .createNamedQuery("WorkRequests." + NormalizedEntity.NAMED_QUERY_ID, WorkRequests.class); query.setParameter("categoryId", ((WorkRequestsPK) idEntity).getCategoryId()); List<WorkRequests> x = query.getResultList(); return x.get(0); } } else { Query query = entityManager.createNativeQuery( "SELECT ORDERS.* FROM CLICKNDONEDB.WORK_REQUESTS ORDERS, CLICKNDONEDB.WORK_REQUESTS_X_END_USERS WHERE CATEGORY_ID = :categoryId", WorkRequests.class); return (WorkRequests) query.getSingleResult(); } }
From source file:ca.uhn.fhir.jpa.dao.BaseHapiFhirDao.java
protected TagDefinition getTag(TagTypeEnum theTagType, String theScheme, String theTerm, String theLabel) { CriteriaBuilder builder = myEntityManager.getCriteriaBuilder(); CriteriaQuery<TagDefinition> cq = builder.createQuery(TagDefinition.class); Root<TagDefinition> from = cq.from(TagDefinition.class); //@formatter:off if (isNotBlank(theScheme)) { cq.where(builder.and(builder.equal(from.get("myTagType"), theTagType), builder.equal(from.get("mySystem"), theScheme), builder.equal(from.get("myCode"), theTerm))); } else {//from w w w. j a v a 2s .c om cq.where(builder.and(builder.equal(from.get("myTagType"), theTagType), builder.isNull(from.get("mySystem")), builder.equal(from.get("myCode"), theTerm))); } //@formatter:on TypedQuery<TagDefinition> q = myEntityManager.createQuery(cq); try { return q.getSingleResult(); } catch (NoResultException e) { TagDefinition retVal = new TagDefinition(theTagType, theScheme, theTerm, theLabel); myEntityManager.persist(retVal); return retVal; } }
From source file:org.openmeetings.app.data.user.Usermanagement.java
public Users getUserByIdAndDeleted(Long id) throws Exception { log.debug("Usermanagement.getUserById"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Predicate condition = cb.equal(c.get("user_id"), id); cq.where(condition);/* ww w . j av a2 s . c o m*/ TypedQuery<Users> q = em.createQuery(cq); Users u = null; try { u = q.getSingleResult(); } catch (NoResultException e) { // u=null} } return u; }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * @author o.becherer Find User by LoginName (test existence of a active * user with login - name/*from w ww . j a va 2 s .co m*/ */ // ----------------------------------------------------------------------------------------------------- public Users getUserByLogin(String login) throws Exception { log.debug("Usermanagement.getUserByLogin : " + login); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Predicate condition = cb.equal(c.get("deleted"), "false"); Predicate subCondition = cb.equal(c.get("login"), login); cq.where(condition, subCondition); TypedQuery<Users> q = em.createQuery(cq); Users u = null; try { u = q.getSingleResult(); } catch (NoResultException e) { // u=null} } return u; }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * //from w ww . ja v a2 s . com * Find User by Id */ // ----------------------------------------------------------------------------------------------------- public Users getUserById(Long id) { log.debug("Usermanagement.getUserById"); if (id == null || id <= 0) { return null; } CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Users> cq = cb.createQuery(Users.class); Root<Users> c = cq.from(Users.class); Predicate condition = cb.equal(c.get("deleted"), "false"); Predicate subCondition = cb.equal(c.get("user_id"), id); cq.where(condition, subCondition); TypedQuery<Users> q = em.createQuery(cq); Users u = null; try { u = q.getSingleResult(); } catch (NoResultException e) { // u=null} } catch (NonUniqueResultException ex) { } return u; }
From source file:com.enioka.jqm.api.HibernateClient.java
@Override public List<com.enioka.jqm.api.JobInstance> getJobs(Query query) { if ((query.getFirstRow() != null || query.getPageSize() != null) && query.isQueryLiveInstances() && query.isQueryHistoryInstances()) { throw new JqmInvalidRequestException("cannot use paging on live instances"); }//from ww w .ja v a 2s .co m if (query.isQueryLiveInstances() && query.isQueryHistoryInstances() && query.getSorts().size() > 0) { throw new JqmInvalidRequestException( "cannot use sorting when querying both live and historical instances"); } EntityManager em = null; try { em = getEm(); // Not using CriteriaBuilder - too much hassle for too little benefit String wh = ""; Map<String, Object> prms = new HashMap<String, Object>(); // String predicates wh += getStringPredicate("userName", query.getUser(), prms); wh += getStringPredicate("sessionId", query.getSessionId(), prms); wh += getStringPredicate("instanceKeyword1", query.getInstanceKeyword1(), prms); wh += getStringPredicate("instanceKeyword2", query.getInstanceKeyword2(), prms); wh += getStringPredicate("instanceKeyword3", query.getInstanceKeyword3(), prms); wh += getStringPredicate("instanceModule", query.getInstanceModule(), prms); wh += getStringPredicate("instanceApplication", query.getInstanceApplication(), prms); // Integer wh += getIntPredicate("parentId", query.getParentId(), prms); wh += getIntPredicate("id", query.getJobInstanceId(), prms); wh += getIntPredicate("queue.id", query.getQueueId() == null ? null : query.getQueueId(), prms); // Now, run queries... List<com.enioka.jqm.api.JobInstance> res2 = new ArrayList<com.enioka.jqm.api.JobInstance>(); // //////////////////////////////////////// // Job Instance query if (query.isQueryLiveInstances()) { // Sort String sort = ""; for (SortSpec s : query.getSorts()) { sort += s.col.getJiField() == null ? "" : ",h." + s.col.getJiField() + " " + (s.order == Query.SortOrder.ASCENDING ? "ASC" : "DESC"); } if (sort.isEmpty()) { sort = " ORDER BY h.id"; } else { sort = " ORDER BY " + sort.substring(1); } // Finish query string String wh2 = "" + wh; Map<String, Object> prms2 = new HashMap<String, Object>(); prms2.putAll(prms); wh2 += getStringPredicate("queue.name", query.getQueueName(), prms2); // tag fields should be looked for in linked object for active JI wh2 += getStringPredicate("jd.applicationName", query.getApplicationName(), prms2); wh2 += getStringPredicate("jd.keyword1", query.getJobDefKeyword1(), prms2); wh2 += getStringPredicate("jd.keyword2", query.getJobDefKeyword2(), prms2); wh2 += getStringPredicate("jd.keyword3", query.getJobDefKeyword3(), prms2); wh2 += getStringPredicate("jd.module", query.getJobDefModule(), prms2); wh2 += getStringPredicate("jd.application", query.getJobDefApplication(), prms2); wh2 += getStringPredicate("node.name", query.getNodeName(), prms2); // Calendar fields are specific (no common fields between History and JobInstance) wh2 += getCalendarPredicate("creationDate", query.getEnqueuedAfter(), ">=", prms2); wh2 += getCalendarPredicate("creationDate", query.getEnqueuedBefore(), "<=", prms2); wh2 += getCalendarPredicate("executionDate", query.getBeganRunningAfter(), ">=", prms2); wh2 += getCalendarPredicate("executionDate", query.getBeganRunningBefore(), "<=", prms2); wh2 += getStatusPredicate("state", query.getStatus(), prms2); if (wh2.length() >= 3) { wh2 = " WHERE " + wh2.substring(3); } TypedQuery<JobInstance> q2 = em.createQuery( "SELECT h FROM JobInstance h LEFT JOIN FETCH h.jd LEFT JOIN FETCH h.node " + wh2 + sort, JobInstance.class); for (Map.Entry<String, Object> entry : prms2.entrySet()) { q2.setParameter(entry.getKey(), entry.getValue()); } if (query.getFirstRow() != null) { q2.setFirstResult(query.getFirstRow()); } if (query.getPageSize() != null) { q2.setMaxResults(query.getPageSize()); } if (query.getFirstRow() != null || query.getPageSize() != null) { TypedQuery<Long> qCount = em.createQuery("SELECT COUNT(h) FROM JobInstance h " + wh2, Long.class); for (Map.Entry<String, Object> entry : prms2.entrySet()) { qCount.setParameter(entry.getKey(), entry.getValue()); } query.setResultSize(new BigDecimal(qCount.getSingleResult()).intValueExact()); } for (JobInstance ji : q2.getResultList()) { res2.add(getJob(ji, em)); } } // //////////////////////////////////////// // History query if (query.isQueryHistoryInstances()) { wh += getStringPredicate("queueName", query.getQueueName(), prms); // tag fields should be looked directly in the denormalized fields for history. wh += getStringPredicate("applicationName", query.getApplicationName(), prms); wh += getStringPredicate("keyword1", query.getJobDefKeyword1(), prms); wh += getStringPredicate("keyword2", query.getJobDefKeyword2(), prms); wh += getStringPredicate("keyword3", query.getJobDefKeyword3(), prms); wh += getStringPredicate("module", query.getJobDefModule(), prms); wh += getStringPredicate("application", query.getJobDefApplication(), prms); wh += getStringPredicate("nodeName", query.getNodeName(), prms); // Calendar fields are specific (no common fields between History and JobInstance) wh += getCalendarPredicate("enqueueDate", query.getEnqueuedAfter(), ">=", prms); wh += getCalendarPredicate("enqueueDate", query.getEnqueuedBefore(), "<=", prms); wh += getCalendarPredicate("executionDate", query.getBeganRunningAfter(), ">=", prms); wh += getCalendarPredicate("executionDate", query.getBeganRunningBefore(), "<=", prms); wh += getCalendarPredicate("endDate", query.getEndedAfter(), ">=", prms); wh += getCalendarPredicate("endDate", query.getEndedBefore(), "<=", prms); wh += getStatusPredicate("status", query.getStatus(), prms); if (wh.length() >= 3) { wh = " WHERE " + wh.substring(3); } // Order by String sort = ""; for (SortSpec s : query.getSorts()) { sort += ",h." + s.col.getHistoryField() + " " + (s.order == Query.SortOrder.ASCENDING ? "ASC" : "DESC"); } if (sort.isEmpty()) { sort = " ORDER BY h.id"; } else { sort = " ORDER BY " + sort.substring(1); } TypedQuery<History> q1 = em.createQuery( "SELECT h FROM History h LEFT JOIN FETCH h.jd LEFT JOIN FETCH h.node LEFT JOIN FETCH h.queue " + wh + sort, History.class); for (Map.Entry<String, Object> entry : prms.entrySet()) { q1.setParameter(entry.getKey(), entry.getValue()); } if (query.getFirstRow() != null) { q1.setFirstResult(query.getFirstRow()); } if (query.getPageSize() != null) { q1.setMaxResults(query.getPageSize()); } if (query.getFirstRow() != null || query.getPageSize() != null) { TypedQuery<Long> qCount = em.createQuery("SELECT COUNT(h) FROM History h " + wh, Long.class); for (Map.Entry<String, Object> entry : prms.entrySet()) { qCount.setParameter(entry.getKey(), entry.getValue()); } query.setResultSize(new BigDecimal(qCount.getSingleResult()).intValueExact()); } // Optimization: fetch messages and parameters in one go. List<History> results = q1.getResultList(); List<Integer> ids = new ArrayList<Integer>(); for (History ji : results) { ids.add(ji.getId()); } if (!ids.isEmpty()) { List<RuntimeParameter> rps = em .createQuery("SELECT rp FROM RuntimeParameter rp WHERE rp.ji IN (:p)", RuntimeParameter.class) .setParameter("p", ids).getResultList(); List<Message> msgs = em .createQuery("SELECT rp FROM Message rp WHERE rp.ji IN (:p)", Message.class) .setParameter("p", ids).getResultList(); for (History ji : results) { res2.add(getJob(ji, em, rps, msgs)); } } } query.setResults(res2); return res2; } catch (Exception e) { throw new JqmClientException("an error occured during query execution", e); } finally { closeQuietly(em); } }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * @param hash/*from ww w. ja v a 2 s . com*/ * @return */ public Users getUserByActivationHash(String hash) { try { String hql = "SELECT u FROM Users as u " + " where u.activatehash = :activatehash" + " AND u.deleted <> :deleted"; TypedQuery<Users> query = em.createQuery(hql, Users.class); query.setParameter("activatehash", hash); query.setParameter("deleted", "true"); Users u = null; try { u = query.getSingleResult(); } catch (NoResultException e) { // u=null} } return u; } catch (Exception e) { log.error("[getUserByActivationHash]", e); } return null; }
From source file:org.openmeetings.app.data.user.Usermanagement.java
/** * get user-role 1 - user 2 - moderator 3 - admin * // www. j ava 2 s .c om * @param user_id * @return */ public Long getUserLevelByID(Long user_id) { try { if (user_id == null) return new Long(0); // For direct access of linked users if (user_id == -1) { return new Long(1); } TypedQuery<Users> query = em.createQuery( "select c from Users as c where c.user_id = :user_id AND c.deleted <> 'true'", Users.class); query.setParameter("user_id", user_id); Users us = null; try { us = query.getSingleResult(); } catch (NoResultException e) { // u=null} } if (us != null) { return us.getLevel_id(); } else { return -1L; } } catch (Exception ex2) { log.error("[getUserLevelByID]", ex2); } return null; }