Java 类javax.persistence.TypedQuery 实例源码

项目:full-javaee-app    文件:CertificationPersistence.java   
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;
}
项目:tap17-muggl-javaee    文件:RequestBeanQueries.java   
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);
    }
}
项目:oscm    文件:BillingDataRetrievalServiceBean.java   
@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();
}
项目:tap17-muggl-javaee    文件:RequestBeanQueries.java   
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);
    }
}
项目:LivroJavaComoProgramar10Edicao    文件:AddressBook.java   
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);
}
项目:BecomeJavaHero    文件:PublisherDAOImpl.java   
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;
}
项目:oscm-app    文件:TemplateFileDAO.java   
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();
    }
}
项目:oscm    文件:AuditLogDao.java   
/**
 * 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();
}
项目:BecomeJavaHero    文件:BookDAOImpl.java   
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;
}
项目:programacion4-final    文件:ControllerReports.java   
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);
        }
    }
项目:phoenix-hibernate-dialect    文件:PhoenixDialectTest.java   
@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);
}
项目:osc-core    文件:JobEntityManager.java   
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);
        }
    }
项目:xsharing-services-router    文件:RouteLegRepositoryImpl.java   
/**
 * 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);
    }
}
项目:full-javaee-app    文件:ConversationDataAccessObject.java   
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;
}
项目:strqlbuilder    文件:StrQLBuilderJPQLTest.java   
@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())));
   }
项目:Trabalhos-FIAP    文件:UsuarioDao.java   
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;
    }
}
项目:Building-Web-Apps-with-Spring-5-and-Angular    文件:UserDAOImpl.java   
@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();
    }
项目:full-javaee-app    文件:CandidatePersistence.java   
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;
}
项目:Trabalhos-FIAP    文件:TransacaoDao.java   
/**
 * 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;
    }
}
项目:tap17-muggl-javaee    文件:RequestBean.java   
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);
    }
}
项目:bootstrap    文件:PaginationDao.java   
/**
 * 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);
}
项目:oscm    文件:ConfigurationServicePaymentInfoTest.java   
@Before
public void setup() throws Exception {
    csb = new ConfigurationServiceBean();
    ds = mock(DataService.class);
    csb.dm = ds;
    query = mock(TypedQuery.class);
}
项目:Building-Web-Apps-with-Spring-5-and-Angular    文件:UserDAOImpl.java   
@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();
}
项目:demo-ang2    文件:PersonEndpoint.java   
@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;
}
项目:Android_Code_Arbiter    文件:MethodUnknownSource.java   
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();
}
项目:full-javaee-app    文件:WeeklyStatsDataAccessObject.java   
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;
}
项目:Building-Web-Apps-with-Spring-5-and-Angular    文件:UserDAOImpl.java   
@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();
}
项目:testing_security_development_enterprise_systems    文件:CategoryEjb.java   
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;
    }
项目:112016.pizzeria-app    文件:ClientService.java   
/***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);
}
项目:testing_security_development_enterprise_systems    文件:UserEJB.java   
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();
    }
项目:linq    文件:JpaUtil.java   
@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);
    }
}
项目:xm-commons    文件:PermittedRepository.java   
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));
}
项目:mid-tier    文件:AccountArchivist.java   
@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();
}
项目:soapbox-race-core    文件:ProductDAO.java   
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();
}
项目:tap17-muggl-javaee    文件:RequestBean.java   
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();
}
项目:mid-tier    文件:CustomerArchivist.java   
/**
 * 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();
}
项目:tap17-muggl-javaee    文件:RequestBean.java   
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;
    }
项目:optashift-employee-rostering    文件:ShiftRestServiceImpl.java   
@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);
    }
}
项目:soapbox-race-core    文件:LobbyDAO.java   
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();
}
项目:Android_Code_Arbiter    文件:JpaSql.java   
public void getUserByUsernameAlt2(String username) {
    TypedQuery<UserEntity> q = em.createQuery(
            "select * from Users where name = '" + username + "'",
            UserEntity.class);

    UserEntity res = q.getSingleResult();
}