Java Code Examples for javax.persistence.NoResultException

The following examples show how to use javax.persistence.NoResultException. These examples are extracted from open source projects. 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
@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 Project: pragmatic-microservices-lab   Source File: JpaCargoRepository.java    License: 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 3
Source Project: monolith   Source File: PerformanceEndpoint.java    License: 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 4
Source Project: monolith   Source File: TicketEndpoint.java    License: 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 5
Source Project: SeaCloudsPlatform   Source File: VariableDAOJpa.java    License: 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
@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 7
Source Project: ranger   Source File: BaseDao.java    License: 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 8
Source Project: SeaCloudsPlatform   Source File: ServiceDAOJpa.java    License: 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 9
/**
 * 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 10
Source Project: webanno   Source File: AnnotationSchemaServiceImpl.java    License: 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 11
Source Project: ranger   Source File: XXPolicyItemDao.java    License: 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 12
Source Project: SeaCloudsPlatform   Source File: BreachDAOJpa.java    License: 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 Project: gemfirexd-oss   Source File: JpaTradeResult.java    License: 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 14
Source Project: cloud-sfsf-benefits-ext   Source File: UserPointsDAO.java    License: 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 15
Source Project: cloud-espm-v2   Source File: CustomerProcessor.java    License: 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 16
Source Project: CargoTracker-J12015   Source File: JpaCargoRepository.java    License: 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 17
@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 18
Source Project: james-project   Source File: JPAAnnotationMapper.java    License: 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 19
@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 20
@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 21
@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 22
@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 23
@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 24
Source Project: wow-auctions   Source File: WoWBusinessBean.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public Optional<Realm> findRealmByNameOrSlug(String name, Realm.Region region) {
    Optional<Realm> realm;
    try {
        realm = Optional.of((Realm) em.createNamedQuery("Realm.findByNameOrSlugInRegion")
                                      .setParameter("name", name)
                                      .setParameter("slug", name)
                                      .setParameter("region", region)
                                      .getSingleResult());
    } catch (NoResultException e) {
        realm = Optional.empty();
    }
    return realm;
}
 
Example 25
Source Project: monolith   Source File: PerformanceEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/{id:[0-9][0-9]*}")
@Consumes("application/json")
public Response update(@PathParam("id") Long id, PerformanceDTO dto)
{
   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;
   }
   entity = dto.fromDTO(entity, em);
   try
   {
      entity = em.merge(entity);
   }
   catch (OptimisticLockException e)
   {
      return Response.status(Response.Status.CONFLICT).entity(e.getEntity()).build();
   }
   return Response.noContent().build();
}
 
Example 26
Source Project: webanno   Source File: AnnotationSchemaServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean existsTag(String aTagName, TagSet aTagSet)
{

    try {
        getTag(aTagName, aTagSet);
        return true;
    }
    catch (NoResultException e) {
        return false;
    }
}
 
Example 27
Source Project: ranger   Source File: XXResourceDefDao.java    License: Apache License 2.0 5 votes vote down vote up
public List<XXResourceDef> findByPolicyId(Long policyId) {
	if(policyId == null) {
		return new ArrayList<XXResourceDef>();
	}
	try {
		return getEntityManager()
				.createNamedQuery("XXResourceDef.findByPolicyId", tClass)
				.setParameter("policyId", policyId).getResultList();
	} catch (NoResultException e) {
		return new ArrayList<XXResourceDef>();
	}
}
 
Example 28
@Override
public Page<StockProduct> get(String indexId, String exchangeId, MarketId marketId, String startWith, Specification<StockProduct> spec, Pageable pageable, boolean validResults) {
	if(!StringUtils.isEmpty(indexId)){
		Index index = indexRepository.findOne(indexId);
		if(index == null){
			throw new NoResultException("No result found for the index ID "+indexId+" !");
		}
		return stockProductRepository.findByIndices(index, pageable);
	}

	if(!StringUtils.isEmpty(startWith)){
		spec = Specifications.where(spec).and(new ProductSpecifications<StockProduct>().nameStartsWith(startWith));
	}
	
	if(marketId != null){
		Market market = marketRepository.findOne(marketId);
		if(market == null){
			throw new NoResultException("No result found for the market ID "+marketId+" !");
		}
		spec = Specifications.where(spec).and(new ProductSpecifications<StockProduct>().marketIdEquals(marketId));
	}
	
	if(!StringUtils.isEmpty(exchangeId)){
		spec = Specifications.where(spec).and(new ProductSpecifications<StockProduct>().exchangeIdEquals(exchangeId));
	}
	
	spec = Specifications.where(spec)
			.and(new ProductSpecifications<StockProduct>().nameNotNull())
			.and(new ProductSpecifications<StockProduct>().exchangeNotNull());

	if(validResults){
		spec = Specifications.where(spec)
				.and(new ProductSpecifications<StockProduct>().currencyNotNull())
				.and(new ProductSpecifications<StockProduct>().hasAPrice());
	}
	
	return stockProductRepository.findAll(spec, pageable);
}
 
Example 29
@Transactional
public RegularExpression findByName(String name) throws DataAccessException {
	try {
		Query query = createNamedQuery("RegularExpression.findByName", -1, -1, name);
		return (RegularExpression) query.getSingleResult();
	} catch (NoResultException nre) {
		return null;
	}

}
 
Example 30
@Transactional
public Department findByName(String name) throws DataAccessException {
	try {
		Query query = createNamedQuery("Department.findByName", -1, -1, name);
		return (Department) query.getSingleResult();
	} catch (NoResultException nre) {
		return null;
	}

}