javax.persistence.NoResultException Java Examples

The following examples show how to use javax.persistence.NoResultException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GreetingServiceTest.java    From spring-security-fundamentals with Apache License 2.0 8 votes vote down vote up
@Test
public void testUpdateNotFound() {

    Exception exception = null;

    Greeting entity = new Greeting();
    entity.setId(Long.MAX_VALUE);
    entity.setText("test");

    try {
        service.update(entity);
    } catch (NoResultException e) {
        exception = e;
    }

    Assert.assertNotNull("failure - expected exception", exception);
    Assert.assertTrue("failure - expected NoResultException",
            exception instanceof NoResultException);

}
 
Example #2
Source File: CustomerDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Customer findCustomerByName(String name, String lastName) {
               Customer customer = null;
	try {
		
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Customer> query = session.createQuery("from Customer where FirstName=:name and LastName=:lastName", Customer.class);
		query.setParameter("name", name);
		query.setParameter("lastName", lastName);
		query.setMaxResults(1);
                       
		customer = query.getSingleResult();
		logging.setMessage("CustomerDaoImpl -> fetching customer with name :" + name);
	} catch (NoResultException e) {
		final InformationFrame frame = new InformationFrame();
		frame.setMessage("Customers not found! :" +e.getLocalizedMessage());
		frame.setVisible(true);
	} finally {
		session.close();
	}
               return customer;
}
 
Example #3
Source File: ServiceDAOJpa.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
@Override
public IService getByName(String name) {
    try {
        TypedQuery<IService> query = entityManager.createNamedQuery(
                Service.QUERY_FIND_BY_NAME, IService.class);
        query.setParameter("name", name);
        IService service = new Service();

        service = (Service) query.getSingleResult();
        System.out.println("Service uuid:" + service.getUuid());

        return service;

    } catch (NoResultException e) {
        logger.debug("No Result found: " + e);
        return null;
    }
}
 
Example #4
Source File: ThemeStatisticsDAOImpl.java    From Asqatasun with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Long findResultCountByResultTypeAndTheme(
        WebResource webResource,
        TestSolution testSolution,
        Theme theme) {
    Query query = entityManager.createQuery(
            "SELECT count(pr.id)FROM "
            + getWebResourceEntityClass().getName() + " r"
            + JOIN_PROCESS_RESULT
            + JOIN_TEST
            + " JOIN t.criterion cr"
            + " JOIN cr.theme th"
            + " WHERE (r.id=:id OR r.parent.id=:id)"
            + " AND pr.definiteValue = :value"
            + " AND th = :theme");
    query.setParameter("id", webResource.getId());
    query.setParameter("value", testSolution);
    query.setParameter("theme", theme);
    try {
        return (Long)query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}
 
Example #5
Source File: VariableDAOJpa.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
@Override
public IVariable getByName(String name) {
    try {
        TypedQuery<IVariable> query = entityManager.createNamedQuery(
                Variable.QUERY_FIND_BY_NAME, IVariable.class);
        query.setParameter("name", name);
        IVariable variable = new Variable();

        variable = query.getSingleResult();
        

        return variable;

    } catch (NoResultException e) {
        logger.debug("No Result found: " + e);
        return null;
    }
}
 
Example #6
Source File: CustomerProcessor.java    From cloud-espm-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Function Import implementation for getting customer by email address
 * 
 * @param emailAddress
 *            email address of the customer
 * @return customer entity.
 * @throws ODataException
 */
@SuppressWarnings("unchecked")
@EdmFunctionImport(name = "GetCustomerByEmailAddress", entitySet = "Customers", returnType = @ReturnType(type = Type.ENTITY, isCollection = true))
public List<Customer> getCustomerByEmailAddress(
		@EdmFunctionImportParameter(name = "EmailAddress") String emailAddress) throws ODataException {
	EntityManagerFactory emf = Utility.getEntityManagerFactory();
	EntityManager em = emf.createEntityManager();
	List<Customer> custList = null;
	try {

		Query query = em.createNamedQuery("Customer.getCustomerByEmailAddress");
		query.setParameter("emailAddress", emailAddress);

		try {

			custList = query.getResultList();
			return custList;

		} catch (NoResultException e) {
			throw new ODataApplicationException("No matching customer with Email Address:" + emailAddress,
					Locale.ENGLISH, HttpStatusCodes.BAD_REQUEST, e);
		}
	} finally {
		em.close();
	}
}
 
Example #7
Source File: JpaCargoRepository.java    From CargoTracker-J12015 with MIT License 6 votes vote down vote up
@Override
public Cargo find(TrackingId trackingId) {
    Cargo cargo;

    try {
        cargo = entityManager.createNamedQuery("Cargo.findByTrackingId",
                Cargo.class)
                .setParameter("trackingId", trackingId)
                .getSingleResult();
    } catch (NoResultException e) {
        logger.log(Level.FINE, "Find called on non-existant tracking ID.", e);
        cargo = null;
    }

    return cargo;
}
 
Example #8
Source File: UserPointsDAO.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
public UserPoints getUserPoints(String userId, long campaignId) {
	final EntityManager em = emProvider.get();
	TypedQuery<UserPoints> query = em.createNamedQuery(DBQueries.GET_USER_POINTS, UserPoints.class);

	query.setParameter("userId", userId); //$NON-NLS-1$
	query.setParameter("campaignId", campaignId); //$NON-NLS-1$
	UserPoints result = null;
	try {
		result = query.getSingleResult();
	} catch (NoResultException x) {
		logger.debug("Could not retrieve user points for userId {} from table {}.", userId, "User"); //$NON-NLS-1$ //$NON-NLS-2$
	} catch (NonUniqueResultException e) {
		throw new IllegalStateException(String.format("More than one entity for userId %s from table User.", userId)); //$NON-NLS-1$
	}
	return result;
}
 
Example #9
Source File: PostingDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getTotalCashEuroPostingsForOneDay(String today) {
    String totalCash = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery("select sum(price) from Posting where currency = 'EURO' and dateTime >= :today", String.class);
        query.setParameter("today", today);
        totalCash = query.getSingleResult();

        logging.setMessage("PostingDaoImpl -> fetching total cash dollar posting for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PostingDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCash;
}
 
Example #10
Source File: JPAAnnotationMapper.java    From james-project with Apache License 2.0 6 votes vote down vote up
private List<MailboxAnnotation> getFilteredLikes(final JPAId jpaId, Set<MailboxAnnotationKey> keys, final Function<MailboxAnnotationKey, Predicate<MailboxAnnotation>> predicateFunction) {
    try {
        return keys.stream()
            .flatMap(key -> getEntityManager()
                .createNamedQuery("retrieveByKeyLike", JPAMailboxAnnotation.class)
                .setParameter("idParam", jpaId.getRawId())
                .setParameter("keyParam", key.asString() + '%')
                .getResultList()
                .stream()
                .map(READ_ROW)
                .filter(predicateFunction.apply(key)))
            .collect(Guavate.toImmutableList());
    } catch (NoResultException e) {
        return ImmutableList.of();
    }
}
 
Example #11
Source File: BaseDao.java    From ranger with Apache License 2.0 6 votes vote down vote up
public List<T> findByNamedQuery(String namedQuery, String paramName,
		Object refId) {
	List<T> ret = new ArrayList<T>();

	if (namedQuery == null) {
		return ret;
	}
	try {
		TypedQuery<T> qry = getEntityManager().createNamedQuery(namedQuery, tClass);
		qry.setParameter(paramName, refId);
		ret = qry.getResultList();
	} catch (NoResultException e) {
		// ignore
	}
	return ret;
}
 
Example #12
Source File: BreachDAOJpa.java    From SeaCloudsPlatform with Apache License 2.0 6 votes vote down vote up
public Breach getBreachByUUID(UUID uuid) {
    try {
        Query query = entityManager
                .createNamedQuery(Breach.QUERY_FIND_BY_UUID);
        query.setParameter("uuid", uuid);
        Breach breach = null;

        breach = (Breach) query.getSingleResult();

        return breach;

    } catch (NoResultException e) {
        logger.debug("No Result found: " + e);
        return null;
    }
}
 
Example #13
Source File: BaseController.java    From spring-security-fundamentals with Apache License 2.0 6 votes vote down vote up
/**
 * Handles JPA NoResultExceptions thrown from web service controller
 * methods. Creates a response with Exception Attributes as JSON and HTTP
 * status code 404, not found.
 * 
 * @param noResultException A NoResultException instance.
 * @param request The HttpServletRequest in which the NoResultException was
 *        raised.
 * @return A ResponseEntity containing the Exception Attributes in the body
 *         and HTTP status code 404.
 */
@ExceptionHandler(NoResultException.class)
public ResponseEntity<Map<String, Object>> handleNoResultException(
        NoResultException noResultException, HttpServletRequest request) {

    logger.info("> handleNoResultException");

    ExceptionAttributes exceptionAttributes = new DefaultExceptionAttributes();

    Map<String, Object> responseBody = exceptionAttributes
            .getExceptionAttributes(noResultException, request,
                    HttpStatus.NOT_FOUND);

    logger.info("< handleNoResultException");
    return new ResponseEntity<Map<String, Object>>(responseBody,
            HttpStatus.NOT_FOUND);
}
 
Example #14
Source File: PostingDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getTotalCreditPoundPostingsForOneDay(String date) {
    String totalCredit = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery("select sum(price) from Posting where "
                + "currency = 'CREDIT CARD' and currency = 'POUND' and dateTime >= :date", String.class);
        query.setParameter("date", date);
        totalCredit = query.getSingleResult();

        logging.setMessage("PostingDaoImpl -> fetching total credit card pound posting for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PostingDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCredit;
}
 
Example #15
Source File: TicketEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id)
{
   TypedQuery<Ticket> findByIdQuery = em.createQuery("SELECT DISTINCT t FROM Ticket t LEFT JOIN FETCH t.ticketCategory WHERE t.id = :entityId ORDER BY t.id", Ticket.class);
   findByIdQuery.setParameter("entityId", id);
   Ticket entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   TicketDTO dto = new TicketDTO(entity);
   return Response.ok(dto).build();
}
 
Example #16
Source File: PerformanceEndpoint.java    From monolith with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{id:[0-9][0-9]*}")
@Produces("application/json")
public Response findById(@PathParam("id") Long id)
{
   TypedQuery<Performance> findByIdQuery = em.createQuery("SELECT DISTINCT p FROM Performance p LEFT JOIN FETCH p.show WHERE p.id = :entityId ORDER BY p.id", Performance.class);
   findByIdQuery.setParameter("entityId", id);
   Performance entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   PerformanceDTO dto = new PerformanceDTO(entity);
   return Response.ok(dto).build();
}
 
Example #17
Source File: XXPolicyItemDao.java    From ranger with Apache License 2.0 6 votes vote down vote up
public List<XXPolicyItem> findByServiceId(Long serviceId) {
	if (serviceId == null) {
		return new ArrayList<XXPolicyItem>();
	}
	try {
		List<XXPolicyItem> returnList = getEntityManager()
				.createNamedQuery("XXPolicyItem.findByServiceId", tClass)
				.setParameter("serviceId", serviceId).getResultList();
		if (returnList == null) {
			return new ArrayList<XXPolicyItem>();
		}
		return returnList;
	} catch (NoResultException e) {
		return new ArrayList<XXPolicyItem>();
	}
}
 
Example #18
Source File: CustomerDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Customer getSinlgeCustomerByReservId(long id, String name) {
	Customer theCustomer = null;
	try {
		session = dataSourceFactory.getSessionFactory().openSession();
		beginTransactionIfAllowed(session);
		Query<Customer> query = session.createQuery("from Customer where ReservationId=:theId and FirstName=:name", Customer.class);
		query.setParameter("theId", id);
		query.setParameter("name", name);
		query.setMaxResults(1);
		
		theCustomer = query.getSingleResult();
		logging.setMessage("CustomerDaoImpl -> fetched customer successfully :"+theCustomer.toString());
                       
	} catch (NoResultException e) {
		final InformationFrame frame = new InformationFrame();
		frame.setMessage("Customers not found!");
		frame.setVisible(true);
	} finally {
		session.close();
	}
          return theCustomer;
}
 
Example #19
Source File: JpaTradeResult.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
protected void invokeFrame1(){
    jpaTxnManager.beginTransaction();
    try {
        //SQL1: select CA_NAME, CA_B_ID, CA_C_ID, CA_TAX_ST from CUSTOMER_ACCOUNT where CA_ID = ?
        //Hibernate: select customerac0_.CA_ID as CA1_9_, customerac0_.CA_B_ID as CA5_9_, customerac0_.CA_BAL as CA2_9_, customerac0_.CA_NAME as CA3_9_, customerac0_.CA_TAX_ST as CA4_9_, customerac0_.CA_C_ID as CA6_9_ from CUSTOMER_ACCOUNT customerac0_ where customerac0_.CA_ID=? fetch first 2 rows only
        //It is not the bug from GemFireXD dialect when you see the fetch first 2 rows only for getSingleResult.
        //It is the hibernate implementation to avoid possible OOME if the setMaxResultSet is not called
        //and set the default resultset to 2 rows.
        customerAccount = (CustomerAccount)entityManager.createQuery(CUSTOMER_ACCOUNT_QUERY).setParameter("caId", toTxnInput.getAcctId()).getSingleResult();
    } catch (NoResultException nre) {
        toTxnOutput.setStatus(-711);
        throw nre;
    } catch (NonUniqueResultException nure) {
        toTxnOutput.setStatus(-711);
        throw nure;
    } catch(RuntimeException re) {
        //Any JPA related exceptions are RuntimeException, catch, log and rethrow.
        throw re;
    }
    //SQL2: select C_F_NAME, C_L_NAME, C_TIER, C_TAX_ID from CUSTOMER where C_ID = ?
    customer = (Customer)customerAccount.getCustomer();
    //SQL3: select B_NAME from BROKER where B_ID = ?
    //Hibernate: select broker0_.B_ID as B1_2_0_, broker0_.B_COMM_TOTAL as B2_2_0_, broker0_.B_NAME as B3_2_0_, broker0_.B_NUM_TRADES as B4_2_0_, broker0_.B_ST_ID as B5_2_0_ from BROKER broker0_ where broker0_.B_ID=?
    broker = (Broker)customerAccount.getBroker();
}
 
Example #20
Source File: PaymentDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Payment getPaymentById(long Id) {
    Payment thePayment = null;
    try {

        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        thePayment = session.get(Payment.class, Id);
        logging.setMessage("PaymentDaoImpl -> fetching payment : " + thePayment.toString());

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return thePayment;
}
 
Example #21
Source File: PaymentDaoImpl.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<Payment> getAllPaymentsByRoomNumber(String theRoomNumber, String string) {
    List<Payment> paymentsList = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Payment> query = session.createQuery("from Payment where "
                + "roomNumber = :theRoomNumber and dateTime >= :localDate", Payment.class);
        query.setParameter("theRoomNumber", theRoomNumber);
        query.setParameter("localDate", string);
        paymentsList = query.getResultList();
        logging.setMessage("PaymentDaoImpl -> fetching all payments...");

    } catch (NoResultException e) {
        logging.setMessage("PaymentDaoImpl Error ->" + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return paymentsList;
}
 
Example #22
Source File: JpaCargoRepository.java    From pragmatic-microservices-lab with MIT License 6 votes vote down vote up
@Override
public Cargo find(TrackingId trackingId) {
    Cargo cargo;

    try {
        cargo = entityManager.createNamedQuery("Cargo.findByTrackingId",
                Cargo.class)
                .setParameter("trackingId", trackingId)
                .getSingleResult();
    } catch (NoResultException e) {
        logger.log(Level.FINE, "Find called on non-existant tracking ID.", e);
        cargo = null;
    }

    return cargo;
}
 
Example #23
Source File: AnnotationSchemaServiceImpl.java    From webanno with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(noRollbackFor = NoResultException.class)
public boolean existsLayer(String aName, Project aProject)
{
    try {
        entityManager
                .createQuery(
                        "FROM AnnotationLayer WHERE name = :name AND project = :project",
                        AnnotationLayer.class)
                .setParameter("name", aName)
                .setParameter("project", aProject)
                .getSingleResult();
        return true;
    }
    catch (NoResultException e) {
        return false;
    }
}
 
Example #24
Source File: DocumentServiceImpl.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(noRollbackFor = NoResultException.class)
public List<AnnotationDocument> listAllAnnotationDocuments(SourceDocument aDocument)
{
    Validate.notNull(aDocument, "Source document must be specified");
    
    return entityManager
            .createQuery(
                    "FROM AnnotationDocument WHERE project = :project AND document = :document",
                    AnnotationDocument.class)
            .setParameter("project", aDocument.getProject())
            .setParameter("document", aDocument)
            .getResultList();
}
 
Example #25
Source File: XXServiceResourceDao.java    From ranger with Apache License 2.0 5 votes vote down vote up
public List<XXServiceResource> findByServiceId(Long serviceId) {
	if (serviceId == null) {
		return new ArrayList<XXServiceResource>();
	}
	try {
		return getEntityManager().createNamedQuery("XXServiceResource.findByServiceId", tClass)
				.setParameter("serviceId", serviceId).getResultList();
	} catch (NoResultException e) {
		return new ArrayList<XXServiceResource>();
	}
}
 
Example #26
Source File: XXTagResourceMapDao.java    From ranger with Apache License 2.0 5 votes vote down vote up
public List<XXTagResourceMap> findByResourceId(Long resourceId) {
	if (resourceId == null) {
		return new ArrayList<XXTagResourceMap>();
	}
	try {
		return getEntityManager().createNamedQuery("XXTagResourceMap.findByResourceId", tClass)
				.setParameter("resourceId", resourceId).getResultList();
	} catch (NoResultException e) {
		return new ArrayList<XXTagResourceMap>();
	}
}
 
Example #27
Source File: BillingDataRetrievalServiceBean.java    From development with Apache License 2.0 5 votes vote down vote up
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public String loadPaymentTypeIdForSubscription(long subscriptionKey) {
    Query query = dm
            .createNamedQuery("SubscriptionHistory.getPaymentTypeId");
    query.setParameter("subscriptionKey", Long.valueOf(subscriptionKey));
    String result;
    try {
        result = (String) query.getSingleResult();
    } catch (NoResultException e) {
        result = "";
    }
    return result;
}
 
Example #28
Source File: ProjectPage.java    From webanno with Apache License 2.0 5 votes vote down vote up
private Optional<Project> getProjectFromParameters(StringValue projectParam)
{
    if (projectParam == null || projectParam.isEmpty()) {
        return Optional.empty();
    }
    
    try {
        return Optional.of(projectService.getProject(projectParam.toLong()));
    }
    catch (NoResultException e) {
        return Optional.empty();
    }
}
 
Example #29
Source File: DataSetDAOImpl.java    From JDeSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@Transactional
public DataSet findById(Long id) throws DataAccessException {
	try {
		Query query = createNamedQuery("DataSet.findById", -1, -1, id);
		return (DataSet) query.getSingleResult();
	} catch (NoResultException nre) {
		return null;
	}

}
 
Example #30
Source File: MCRHIBFileMetadataStore.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String retrieveRootNodeID(String ownerID) throws MCRPersistenceException {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<String> rootQuery = em.createNamedQuery("MCRFSNODES.getRootID", String.class);
    rootQuery.setParameter("owner", ownerID);
    try {
        return rootQuery.getSingleResult();
    } catch (NoResultException e) {
        LOGGER.warn("There is no fsnode with OWNER = {}", ownerID);
        return null;
    }
}