Java Code Examples for javax.persistence.TypedQuery

The following are top voted examples for showing how to use javax.persistence.TypedQuery. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: full-javaee-app   File: CertificationPersistence.java   Source Code and License 8 votes vote down vote up
public static Certifications getByName(String name) {
    if (name != null && !name.isEmpty()) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        String query = "SELECT cert from Certifications cert where cert.certification = :name";

        try {
            TypedQuery<Certifications> q = em.createQuery(query, Certifications.class);
            q.setParameter("name", name);
            return q.getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
    return null;
}
 
Example 2
Project: tap17-muggl-javaee   File: RequestBeanQueries.java   Source Code and License 7 votes vote down vote up
public List<PlayerDetails> getPlayersByPositionAndName(String position, String name) {
    logger.info("getPlayersByPositionAndName");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.equal(player.get(Player_.position), position),
                    cb.equal(player.get(Player_.name), name));
            cq.select(player).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 3
Project: BecomeJavaHero   File: BookDAOImpl.java   Source Code and License 7 votes vote down vote up
public List<BookEntity> findAll() {
	EntityManager em = connection.createEntityManager();
	List<BookEntity> result;
	
	try {
		em.getTransaction().begin();
		TypedQuery<BookEntity> query = em.createQuery("Select b from BookEntity b", BookEntity.class);
		result = query.getResultList();
		em.getTransaction().commit();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
	}
	
	return result;
}
 
Example 4
Project: osc-core   File: JobEntityManager.java   Source Code and License 7 votes vote down vote up
public Long getTaskCount(Long jobId) throws InterruptedException, VmidcException {

        try {
            EntityManager em = this.dbMgr.getTransactionalEntityManager();
            return this.dbMgr.getTransactionControl().required(() -> {

                String hql = "SELECT count(*) FROM TaskRecord WHERE job_fk = :jobId";

                TypedQuery<Long> query = em.createQuery(hql, Long.class);
                query.setParameter("jobId", jobId);
                return query.getSingleResult();
            });
        } catch (ScopedWorkException swe) {
            throw swe.as(RuntimeException.class);
        }
    }
 
Example 5
Project: oscm   File: BillingDataRetrievalServiceBean.java   Source Code and License 6 votes vote down vote up
@Override
@TransactionAttribute(TransactionAttributeType.MANDATORY)
public Date loadPriceModelStartDate(long priceModelKeyForSubscription) {
    TypedQuery<PriceModelHistory> query = dm.createNamedQuery(
            "PriceModelHistory.findByObjectAndProvisioningCompleted",
            PriceModelHistory.class);
    query.setParameter("objKey", Long.valueOf(priceModelKeyForSubscription));
    query.setParameter("provisioningCompleted", Boolean.TRUE);

    List<PriceModelHistory> resultList = query.getResultList();
    if (resultList.isEmpty()) {
        throw new BillingRunFailed(
                "History data is missing for price model with key "
                        + priceModelKeyForSubscription);
    }

    return resultList.get(0).getModdate();
}
 
Example 6
Project: tap17-muggl-javaee   File: RequestBeanQueries.java   Source Code and License 6 votes vote down vote up
public List<PlayerDetails> getAllPlayers() {
    logger.info("getAllPlayers");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);

            cq.select(player);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 7
Project: LivroJavaComoProgramar10Edicao   File: AddressBook.java   Source Code and License 6 votes vote down vote up
private void queryButtonActionPerformed(ActionEvent e)
{
   // query that returns all contacts
   TypedQuery<Addresses> findByLastname = 
      entityManager.createNamedQuery(
         "Addresses.findByLastname", Addresses.class);

   // configure parameter for query
   findByLastname.setParameter("lastname", queryTextField.getText());
   results = findByLastname.getResultList(); // get all addresses
   numberOfEntries = results.size();
   
   if (numberOfEntries != 0)
   {
      currentEntryIndex = 0;
      displayRecord();
      nextButton.setEnabled(true);
      previousButton.setEnabled(true);
   } 
   else
      browseButtonActionPerformed(e);
}
 
Example 8
Project: BecomeJavaHero   File: PublisherDAOImpl.java   Source Code and License 6 votes vote down vote up
public List<PublisherEntity> findAll() {
	EntityManager em = connection.createEntityManager();
	List<PublisherEntity> result;
	
	try {
		em.getTransaction().begin();
		TypedQuery<PublisherEntity> query = em.createQuery("Select p from PublisherEntity p", PublisherEntity.class);
		result = query.getResultList();
		em.getTransaction().commit();
	} finally {
		if (em.getTransaction().isActive()) {
			em.getTransaction().rollback();
		}
		em.close();
	}
	
	return result;
}
 
Example 9
Project: oscm-app   File: TemplateFileDAO.java   Source Code and License 6 votes vote down vote up
public List<TemplateFile> getTemplateFilesByControllerId(
        String controllerId) {

    TypedQuery<TemplateFile> query = em.createNamedQuery(
            "TemplateFile.getForControllerId", TemplateFile.class);
    query.setParameter("controllerId", controllerId);

    try {
        return query.getResultList();
    } catch (NoResultException e) {
        return Collections.emptyList();
    }
}
 
Example 10
Project: oscm   File: AuditLogDao.java   Source Code and License 6 votes vote down vote up
/**
 * count the number of auditLogs by operationIds and date range, if
 * operationIds is null or empty, count the number of AuditLogs only by date
 * range
 * 
 * @param operationIds
 * @param startTime
 * @param endTime
 * @return
 */
public long countAuditLogs(List<String> operationIds, long startTime,
        long endTime) {
    TypedQuery<Number> query;
    if (operationIds == null || operationIds.isEmpty()) {
        query = em.createNamedQuery("AuditLog.countByDateRange",
                Number.class);
    } else {
        query = em.createNamedQuery(
                "AuditLog.countByOperationAndDateRange", Number.class);
        query.setParameter("operationIds", operationIds);
    }
    query.setParameter("startTime", Long.valueOf(startTime));
    query.setParameter("endTime", Long.valueOf(endTime));
    return query.getSingleResult().longValue();
}
 
Example 11
Project: programacion4-final   File: ControllerReports.java   Source Code and License 6 votes vote down vote up
public void loadAll() {

        List<DocumentDetail> ListDocumentDetail = new ArrayList<DocumentDetail>();

        Items it = new Items();
        EntityManager em = it.getEntityManager();
        TypedQuery<DocumentDetail> consultItems = em.createNamedQuery("DocumentDetail.findAll", DocumentDetail.class);
        ListDocumentDetail = consultItems.getResultList();

        ListProducts = new ArrayList<Products>();

        for (DocumentDetail selectedItem : ListDocumentDetail) {
            Products newProduct = new Products();
            newProduct.setArticulo(selectedItem.getItemId().getName());
            newProduct.setBodega(selectedItem.getWarehousesId().getName());
            if (selectedItem.getDocumentId().getTypedocId().getCode().equals("1")) {
                newProduct.setEntradas(selectedItem.getQuantity());
            } else {
                newProduct.setSallidas(selectedItem.getQuantity());

            }
            newProduct.setFecha(selectedItem.getDocumentId().getDocumentDate().toString());
            newProduct.setConsecutivo(selectedItem.getDocumentId().getConsecutive() + "");
            ListProducts.add(newProduct);
        }
    }
 
Example 12
Project: phoenix-hibernate-dialect   File: PhoenixDialectTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test201_Insert() throws Exception {
    em.getTransaction().begin();

    Employee e = new Employee();
    e.setEmpNo(99999);
    e.setFirstName("John");
    e.setLastName("Doe");
    e.setBirthDate(DATE_FORMATTER.parse("2008-04-12"));
    e.setGender(Gender.MALE);
    e.setHireDate(DATE_FORMATTER.parse("2016-01-30"));
    e.setSalaries(null);
    em.persist(e);

    em.getTransaction().commit();

    TypedQuery<Employee> q = em.createQuery("select e from employee e where e.empNo = :empNo", Employee.class);
    q.setParameter("empNo", 99999);
    Employee inserted = q.getSingleResult();
    Assert.assertEquals(e, inserted);
}
 
Example 13
Project: xsharing-services-router   File: RouteLegRepositoryImpl.java   Source Code and License 6 votes vote down vote up
/**
 * HQL version of the query
 */
private <T extends RouteLeg> RouteLeg findRouteLegByFromToHQL(GeoCoord from, GeoCoord to, Class clazz) throws DatabaseException {
    final String bikeQuery = "SELECT leg from BikeLeg leg WHERE leg.from = :fromGeo AND leg.to = :toGeo";
    final String carQuery = "SELECT leg from CarLeg leg WHERE leg.from = :fromGeo AND leg.to = :toGeo";

    try {
        TypedQuery<? extends RouteLeg> query;
        if (clazz == BikeLeg.class) {
            query = entityManager.createQuery(bikeQuery, BikeLeg.class);
        } else {
            query = entityManager.createQuery(carQuery, CarLeg.class);
        }

        List<? extends RouteLeg> resultList = query.setParameter("fromGeo", from)
                                                   .setParameter("toGeo", to)
                                                   .getResultList();

        return extractOne(resultList);

    } catch (IndexOutOfBoundsException e) {
        throw new DatabaseException("Could not find entity " + clazz + " for coordinates " + from + " -> " + to);
    }
}
 
Example 14
Project: full-javaee-app   File: ConversationDataAccessObject.java   Source Code and License 6 votes vote down vote up
public static Conversations getByClientAndCandidateID(int clientID, int candidateID) throws NoResultException {
    if (clientID > 0 && candidateID > 0) {
        EntityManager em = EMFUtil.getEMFactory().createEntityManager();
        String query = "SELECT c FROM Conversations c WHERE c.clientID = :clientID AND c.candidateID = :candidateID";
        try {
            TypedQuery<Conversations> q = em.createQuery(query, Conversations.class);
            q.setParameter("clientID", clientID);
            q.setParameter("candidateID", candidateID);
            Conversations conversation = q.getSingleResult();
            em.close();
            return conversation;
        } finally {
            if (em.isOpen()) {
                em.close();
            }
        }
    }
    return null;
}
 
Example 15
Project: strqlbuilder   File: StrQLBuilderJPQLTest.java   Source Code and License 6 votes vote down vote up
@Test
   public void subSelectTest() {
StrQLBuilder jpa = StrQLBuilder.createJPQL()
	.select("p.id")
	.from("Person p")
	.where("not exists (:jpa)", StrQLBuilder.createNative()
		.select("1")
		.from("Job j")
		.where("j.id = p.id")
		.and("1 = :val", 1)
		.and("exists (:jpa2)", StrQLBuilder.createNative()
			.select("1")
			.from("Person p")
			.where("1 = :val2", 1)));
TypedQuery<Long> query = jpa.createQuery(entityManager, Long.class);
List<Long> persons = query.getResultList();
assertThat(persons, is(not(empty())));
   }
 
Example 16
Project: Trabalhos-FIAP   File: UsuarioDao.java   Source Code and License 5 votes vote down vote up
public Usuario buscarUsuario(String apelido) {
	StringBuilder sb = new StringBuilder();
	sb.append("select u from Usuario u where apelido = '").append(apelido).append("'");
	
	TypedQuery<Usuario> query = super.em.createQuery(sb.toString(), Usuario.class);
	try {
		return query.getSingleResult();
	} catch (NoResultException e) {
		return null;
	}
}
 
Example 17
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: UserDAOImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
    @Override
	public List<User> findByEmail(String email) {
    	Session session = this.sessionFactory.getCurrentSession();
        TypedQuery<User> query = session.getNamedQuery("findByEmail");  
        query.setParameter("email", email);
//    	Query query = session.getNamedQuery("findByEmail");
//    	query.setString("email", email);
        return query.getResultList();
	}
 
Example 18
Project: full-javaee-app   File: CandidatePersistence.java   Source Code and License 5 votes vote down vote up
public static List<Candidates> getApprovalList() {
    EntityManager em = EMFUtil.getEMFactory().createEntityManager();
    String query = "SELECT candidate FROM Candidates candidate WHERE candidate.approved = 'No' OR " +
            "candidate.approved IS NULL";
    TypedQuery<Candidates> qCandidate = em.createQuery(query, Candidates.class);
    List<Candidates> candidates = qCandidate.getResultList();
    em.close();
    return candidates;
}
 
Example 19
Project: Trabalhos-FIAP   File: TransacaoDao.java   Source Code and License 5 votes vote down vote up
/**
 * Listar as transa��es j� efetivadas na conta
 * 
 * @param conta Id do Telegram
 * @param tipoTransacao Tipo de transa��o que deve ser retornada
 * 
 * @return Lista das transa��es
 */
public List<Transacao> buscarTransacoes(long conta, TipoTransacao tipoTransacao) {
	TypedQuery<Transacao> query = super.em.createQuery("select t from Transacao t where conta = " + conta + " and tipo_transacao = " + tipoTransacao.getCodigo(), Transacao.class);
	try {
		return query.getResultList();
	} catch (NoResultException e) {
		return null;
	}
}
 
Example 20
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 5 votes vote down vote up
public List<PlayerDetails> getPlayersBySalaryRange(int low, int high) {
    logger.info("getPlayersBySalaryRange");
    List<Player> players = null;

    try {
        CriteriaQuery<Player> cq = cb.createQuery(Player.class);
        if (cq != null) {
            Root<Player> player = cq.from(Player.class);

            // Get MetaModel from Root
            //EntityType<Player> Player_ = player.getModel();

            // set the where clause
            cq.where(cb.between(player.get(
                    Player_.salary),
                    (double)low,
                    (double)high));
            // set the select clause
            cq.select(player).distinct(true);
            TypedQuery<Player> q = em.createQuery(cq);
            players = q.getResultList();
        }
        return copyPlayersToDetails(players);
    } catch (Exception ex) {
        throw new EJBException(ex);
    }
}
 
Example 21
Project: bootstrap   File: PaginationDao.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new count query for the given {@link Specification}.
 */
private <T> TypedQuery<Long> getCountQuery(final Class<T> entityType, final Specification<T> spec) {

	final CriteriaBuilder builder = em.getCriteriaBuilder();
	final CriteriaQuery<Long> query = builder.createQuery(Long.class);

	final Root<T> root = query.from(entityType);
	applySpecificationToCriteria(root, spec, query);
	query.select(builder.count(root));

	return em.createQuery(query);
}
 
Example 22
Project: oscm   File: ConfigurationServicePaymentInfoTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() throws Exception {
    csb = new ConfigurationServiceBean();
    ds = mock(DataService.class);
    csb.dm = ds;
    query = mock(TypedQuery.class);
}
 
Example 23
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: UserDAOImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<User> findByEmailAndPassword(String email, String password) {
	Session session = this.sessionFactory.getCurrentSession();
	TypedQuery<User> query = session.getNamedQuery("findByEmailAndPassword");  
       query.setParameter("email", email); 
       query.setParameter("password", password);
       return query.getResultList();
}
 
Example 24
Project: demo-ang2   File: PersonEndpoint.java   Source Code and License 5 votes vote down vote up
@GET
@Produces("application/json")
public List<Person> listAll(@QueryParam("start") Integer startPosition,
		@QueryParam("max") Integer maxResult) {
	TypedQuery<Person> findAllQuery = em.createQuery(
			"SELECT DISTINCT p FROM Person p ORDER BY p.id", Person.class);
	if (startPosition != null) {
		findAllQuery.setFirstResult(startPosition);
	}
	if (maxResult != null) {
		findAllQuery.setMaxResults(maxResult);
	}
	final List<Person> results = findAllQuery.getResultList();
	return results;
}
 
Example 25
Project: Android_Code_Arbiter   File: MethodUnknownSource.java   Source Code and License 5 votes vote down vote up
public void getUserByUsername1() {
    String username = unknownSource();

    TypedQuery<UserEntity> q = em.createQuery(
            String.format("select * from Users where name = %s", username),
            UserEntity.class);

    UserEntity res = q.getSingleResult();
}
 
Example 26
Project: full-javaee-app   File: WeeklyStatsDataAccessObject.java   Source Code and License 5 votes vote down vote up
public static List<WeeklyStats> getAll () {
	EntityManager em = EMFUtil.getEMFactory().createEntityManager();
	String statsQuery = "SELECT stats FROM WeeklyStats stats ORDER BY stats.weeklyStatsID DESC";
	TypedQuery<WeeklyStats> qStats = em.createQuery(statsQuery, WeeklyStats.class);
	List<WeeklyStats> list = qStats.getResultList();
       em.close();
       return list;
}
 
Example 27
Project: Building-Web-Apps-with-Spring-5-and-Angular   File: UserDAOImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<User> findByEmailAndPassword(String email, String password) {
	Session session = this.sessionFactory.getCurrentSession();
	TypedQuery<User> query = session.getNamedQuery("findByEmailAndPassword");  
       query.setParameter("email", email); 
       query.setParameter("password", password);
       return query.getResultList();
}
 
Example 28
Project: testing_security_development_enterprise_systems   File: CategoryEjb.java   Source Code and License 5 votes vote down vote up
public List<Category> getAllCategories(boolean withSub){

        TypedQuery<Category> query = em.createQuery("select c from Category c", Category.class);
        List<Category> categories = query.getResultList();

        if(withSub){
            //force loading
            categories.forEach(c -> c.getSubCategories().size());
        }

        return categories;
    }
 
Example 29
Project: 112016.pizzeria-app   File: ClientService.java   Source Code and License 5 votes vote down vote up
/***Supprime un client de la base de donnee***/
public void deleteClient(Integer id){
	TypedQuery<Client> query = em.createQuery("SELECT c FROM Client c WHERE c.id = :id", Client.class);
	query.setParameter("id", id);
	Client c = query.getSingleResult();
	
	em.remove(c);
}
 
Example 30
Project: testing_security_development_enterprise_systems   File: UserEJB.java   Source Code and License 5 votes vote down vote up
public List<User> getTopUsersWithoutCounter(int n) {

        TypedQuery<User> query = em.createQuery(
                "select u from User u order by size(u.posts) + size(u.comments) DESC",
                User.class);
        query.setMaxResults(n);

        return query.getResultList();
    }
 
Example 31
Project: linq   File: JpaUtil.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
/**
 * 分页条件查询
 * @param cq 条件
 * @param pageable 分页信息
 * @param <T> 领域类(实体类)范型
 * @return 分页结果
 */
public static <T> Page<T> findAll(CriteriaQuery<T> cq, Pageable pageable) {
	Class<T> domainClass = cq.getResultType();
	Root<T> root;
	if (CollectionUtils.isEmpty(cq.getRoots())) {
		root = cq.from(domainClass);
	} else {
		root = (Root<T>) cq.getRoots().iterator().next();
	}
	EntityManager em = getEntityManager(domainClass);
	if (pageable == null) {
		List<T> list = findAll(cq);
		return new PageImpl<T>(list);
	} else {
		Sort sort = pageable.getSort();
		cq.orderBy(QueryUtils.toOrders(sort, root, em.getCriteriaBuilder()));
		TypedQuery<T> query = em.createQuery(cq);
		
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

		Long total = count(cq);
		List<T> content = total > pageable.getOffset() ? query.getResultList() : Collections.<T> emptyList();

		return new PageImpl<T>(content, pageable, total);
	}
}
 
Example 32
Project: xm-commons   File: PermittedRepository.java   Source Code and License 5 votes vote down vote up
private <T> Page<T> readPage(TypedQuery<Long> countQuery, TypedQuery<T> query, Pageable pageable) {
    query.setFirstResult(pageable.getOffset());
    query.setMaxResults(pageable.getPageSize());

    return PageableExecutionUtils.getPage(query.getResultList(), pageable,
        () -> executeCountQuery(countQuery));
}
 
Example 33
Project: mid-tier   File: AccountArchivist.java   Source Code and License 5 votes vote down vote up
@LogDuration(limit = 50)
public ReconciledTransaction getReconciledTransaction(String regNo, String accountNo, String id) {
    TypedQuery<ReconciledTransaction> q = em.createQuery("select rt from ReconciledTransaction rt " +
            "where rt.account.regNo=:regNo and rt.account.accountNo=:accountNo and rt.id=:id", ReconciledTransaction.class);
    q.setParameter("regNo", regNo);
    q.setParameter("accountNo", accountNo);
    q.setParameter("id", id);
    return q.getSingleResult();
}
 
Example 34
Project: soapbox-race-core   File: ProductDAO.java   Source Code and License 5 votes vote down vote up
public List<ProductEntity> findByLevelEnabled(String categoryName, String productType, int minLevel, boolean enabled, boolean premium) {
	TypedQuery<ProductEntity> query = entityManager.createNamedQuery("ProductEntity.findByLevelEnabled", ProductEntity.class);
	query.setParameter("categoryName", categoryName);
	query.setParameter("productType", productType);
	query.setParameter("enabled", enabled);
	query.setParameter("minLevel", minLevel);
	query.setParameter("premium", premium);
	return query.getResultList();
}
 
Example 35
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 5 votes vote down vote up
public List<Student> getAllStudents() {
    CriteriaQuery<Student> cq = em.getCriteriaBuilder().createQuery(Student.class);
    Root<Student> student = cq.from(Student.class);
    cq.select(student);
    cq.where(cb.isTrue(student.get(Student_.active)));
    cq.distinct(true);
    TypedQuery<Student> q = em.createQuery(cq);
    return q.getResultList();
}
 
Example 36
Project: mid-tier   File: CustomerArchivist.java   Source Code and License 5 votes vote down vote up
/**
 * Find customer by its semantic key. Note this will throw {@link NoResultException} which will roll back the
 * transaction if the customer is not found - if this is a problem consider using
 * {@link #findCustomer(String)}.
 */
@LogDuration(limit = 50)
public Customer getCustomer(String customerNo) {
    TypedQuery<Customer> q = em.createQuery("select c from Customer c where c.sid=:sid", Customer.class);
    q.setParameter("sid", customerNo);
    return q.getSingleResult();
}
 
Example 37
Project: tap17-muggl-javaee   File: RequestBean.java   Source Code and License 5 votes vote down vote up
public List<String> getSportsOfPlayer(String playerId) {
        logger.info("getSportsOfPlayer");
        List<String> sports = new ArrayList<>();

        try {
            CriteriaQuery<String> cq = cb.createQuery(String.class);
            if (cq != null) {
                Root<Player> player = cq.from(Player.class);
                Join<Player, Team> team = player.join(Player_.teams);
                Join<Team, League> league = team.join(Team_.league);

                // Get MetaModel from Root
                //EntityType<Player> Player_ = player.getModel();

                // set the where clause
                cq.where(cb.equal(player.get(Player_.id), playerId));
                cq.select(league.get(League_.sport)).distinct(true);
                TypedQuery<String> q = em.createQuery(cq);
                sports = q.getResultList();
            }

//        Player player = em.find(Player.class, playerId);
//        Iterator<Team> i = player.getTeams().iterator();
//        while (i.hasNext()) {
//            Team team = i.next();
//            League league = team.getLeague();
//            sports.add(league.getSport());
//        }
        } catch (Exception ex) {
            throw new EJBException(ex);
        }
        return sports;
    }
 
Example 38
Project: optashift-employee-rostering   File: ShiftRestServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public ShiftTemplate getTemplate(Integer tenantId) {
    TypedQuery<ShiftTemplate> q = entityManager.createNamedQuery("ShiftTemplate.get", ShiftTemplate.class);
    q.setParameter("tenantId", tenantId);
    List<ShiftTemplate> result = q.getResultList();
    if (result.isEmpty()) {
        return null;
    } else if (1 != result.size()) {
        throw new IllegalStateException("Each tenant can only have 1 template! Found " + result.size()
                + "templates!");
    } else {
        return result.get(0);
    }
}
 
Example 39
Project: soapbox-race-core   File: LobbyDAO.java   Source Code and License 5 votes vote down vote up
public List<LobbyEntity> findAllOpen() {
	Date dateNow = new Date();
	Date datePast = new Date(dateNow.getTime() - 35000);
	
	TypedQuery<LobbyEntity> query = entityManager.createNamedQuery("LobbyEntity.findAllOpen", LobbyEntity.class);
	query.setParameter("dateTime1", datePast);
	query.setParameter("dateTime2", dateNow);
	return query.getResultList();
}
 
Example 40
Project: Android_Code_Arbiter   File: JpaSql.java   Source Code and License 5 votes vote down vote up
public void getUserByUsernameAlt2(String username) {
    TypedQuery<UserEntity> q = em.createQuery(
            "select * from Users where name = '" + username + "'",
            UserEntity.class);

    UserEntity res = q.getSingleResult();
}