Java Code Examples for javax.persistence.TypedQuery#getResultList()

The following examples show how to use javax.persistence.TypedQuery#getResultList() . 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: BaseEntityService.java    From monolith with Apache License 2.0 6 votes vote down vote up
public List<T> getAll(MultivaluedMap<String, String> queryParameters) {
      final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      final CriteriaQuery<T> criteriaQuery = criteriaBuilder.createQuery(entityClass);
      Root<T> root = criteriaQuery.from(entityClass);
      Predicate[] predicates = extractPredicates(queryParameters, criteriaBuilder, root);
      criteriaQuery.select(criteriaQuery.getSelection()).where(predicates);
      criteriaQuery.orderBy(criteriaBuilder.asc(root.get("id")));
      TypedQuery<T> query = entityManager.createQuery(criteriaQuery);
      if (queryParameters.containsKey("first")) {
      	Integer firstRecord = Integer.parseInt(queryParameters.getFirst("first"))-1;
      	query.setFirstResult(firstRecord);
      }
      if (queryParameters.containsKey("maxResults")) {
      	Integer maxResults = Integer.parseInt(queryParameters.getFirst("maxResults"));
      	query.setMaxResults(maxResults);
      }
return query.getResultList();
  }
 
Example 2
Source File: QueryImpl.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Optional<T> findOne() {
    EntityManager em = database.em();
    try {
        TypedQuery<T> query = em.createQuery(sql.selectSQL(), entityClass);
        for (int i = 0; i < params.size(); i++) {
            query.setParameter(i, params.get(i));
        }
        query.setFirstResult(0);
        query.setMaxResults(1);
        List<T> results = query.getResultList();
        if (results.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(results.get(0));
    } finally {
        em.close();
    }
}
 
Example 3
Source File: CategoryEjb.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 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 4
Source File: EmployeeSearchServiceImpl.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public List<DeptEmployee> filterbyTitleUsingExpression(List<String> titles) {
    CriteriaQuery<DeptEmployee> criteriaQuery = createCriteriaQuery(DeptEmployee.class);
    Root<DeptEmployee> root = criteriaQuery.from(DeptEmployee.class);
    criteriaQuery.select(root)
        .where(root.get("title")
            .in(titles));
    TypedQuery<DeptEmployee> query = entityManager.createQuery(criteriaQuery);
    return query.getResultList();
}
 
Example 5
Source File: JpaRealmProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public List<ClientModel> getAlwaysDisplayInConsoleClients(RealmModel realm) {
    TypedQuery<String> query = em.createNamedQuery("getAlwaysDisplayInConsoleClients", String.class);
    query.setParameter("realm", realm.getId());
    List<String> clients = query.getResultList();
    if (clients.isEmpty()) return Collections.EMPTY_LIST;
    List<ClientModel> list = new LinkedList<>();
    for (String id : clients) {
        ClientModel client = session.realms().getClientById(id, realm);
        if (client != null) list.add(client);
    }
    return Collections.unmodifiableList(list);
}
 
Example 6
Source File: MCRHIBLinkTableStore.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a List of all link sources of <code>to</code> and a special
 * <code>type</code>
 *
 * @param to
 *            Destination-ID
 * @param type
 *            Link reference type, this can be null. Current types are
 *            child, classid, parent, reference and derivate.
 * @return List of Strings (Source-IDs)
 */
@Override
public Collection<String> getSourcesOf(String to, String type) {
    boolean withType = type != null && type.trim().length() != 0;
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<String> toQuery = em.createNamedQuery(
        withType ? "MCRLINKHREF.getSourcesWithType" : "MCRLINKHREF.getSources", String.class);
    toQuery.setParameter("to", to);
    if (withType) {
        toQuery.setParameter("type", type);
    }
    return toQuery.getResultList();
}
 
Example 7
Source File: GroupAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteRoleMapping(RoleModel role) {
    if (group == null || role == null) return;

    TypedQuery<GroupRoleMappingEntity> query = getGroupRoleMappingEntityTypedQuery(role);
    query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
    List<GroupRoleMappingEntity> results = query.getResultList();
    if (results.size() == 0) return;
    for (GroupRoleMappingEntity entity : results) {
        em.remove(entity);
    }
    em.flush();
}
 
Example 8
Source File: AbstractJPATypedQueryVisitorTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected List<Book> queryBooks(String expression,
                              Map<String, String> visitorProps,
                              Map<String, String> parserBinProps,
                              List<String> joinProps) throws Exception {
    SearchCondition<Book> filter = getParser(visitorProps, parserBinProps)
        .parse(expression);
    SearchConditionVisitor<Book, TypedQuery<Book>> jpa =
        new JPATypedQueryVisitor<Book>(em, Book.class, visitorProps, joinProps);
    filter.accept(jpa);
    TypedQuery<Book> query = jpa.getQuery();
    return query.getResultList();
}
 
Example 9
Source File: FooServiceSortingIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void whenSortingFooWithCriteria_thenPrintSortedFoos() {
    final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
    final Root<Foo> from = criteriaQuery.from(Foo.class);
    final CriteriaQuery<Foo> select = criteriaQuery.select(from);
    criteriaQuery.orderBy(criteriaBuilder.asc(from.get("name")));
    final TypedQuery<Foo> typedQuery = entityManager.createQuery(select);
    final List<Foo> fooList = typedQuery.getResultList();
    for (final Foo foo : fooList) {
        System.out.println("Name:" + foo.getName() + "--------Id:" + foo.getId());
    }
}
 
Example 10
Source File: JPAReportDAO.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
@Override
public List<Report> findAll() {
    TypedQuery<Report> query = entityManager().createQuery(
            "SELECT e FROM " + JPAReport.class.getSimpleName() + " e", Report.class);

    return query.getResultList();
}
 
Example 11
Source File: PieceDao.java    From computoser with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<Piece> getPiecesInRange(DateTime start, DateTime end) {
    TypedQuery<Piece> query = getEntityManager().createQuery("SELECT p FROM Piece p WHERE p.generationTime > :start AND p.generationTime < :end", Piece.class);
    query.setParameter("start", start);
    query.setParameter("end", end);

    return query.getResultList();
}
 
Example 12
Source File: DefaultDatabase.java    From BootsFaces-Examples with Apache License 2.0 5 votes vote down vote up
public void readUserTable(EntityManager entityManager) {
	TypedQuery<UserEntity> query = entityManager.createQuery("from UserEntity", UserEntity.class);
	List<UserEntity> resultList = query.getResultList();
	if (false) {
		resultList.stream()
				.forEach(user -> LOGGER.info(user.getId() + " " + user.getName() + " " + user.getEmail()));
		new UserEntity().findAll(entityManager).stream()
				.forEach(user -> LOGGER.info(user.getId() + " " + user.getName() + " " + user.getEmail()));
	}
}
 
Example 13
Source File: UserDAOImpl.java    From Building-Web-Apps-with-Spring-5-and-Angular with MIT 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 14
Source File: JpaUserFederatedStorageProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Set<FederatedIdentityModel> getFederatedIdentities(String userId, RealmModel realm) {
    TypedQuery<BrokerLinkEntity> query = em.createNamedQuery("findBrokerLinkByUser", BrokerLinkEntity.class)
            .setParameter("userId", userId);
    List<BrokerLinkEntity> results = query.getResultList();
    Set<FederatedIdentityModel> set = new HashSet<>();
    for (BrokerLinkEntity entity : results) {
        FederatedIdentityModel model = new FederatedIdentityModel(entity.getIdentityProvider(), entity.getBrokerUserId(), entity.getBrokerUserName(), entity.getToken());
        set.add(model);
    }
    return set;
}
 
Example 15
Source File: JPAAccessTokenDAO.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
@Override
public List<AccessToken> findAll(final int page, final int itemsPerPage, final List<OrderByClause> orderByClauses) {
    StringBuilder queryString = buildFindAllQuery().append(toOrderByStatement(orderByClauses));

    TypedQuery<AccessToken> query = entityManager().createQuery(queryString.toString(), AccessToken.class);

    query.setFirstResult(itemsPerPage * (page <= 0 ? 0 : page - 1));

    if (itemsPerPage > 0) {
        query.setMaxResults(itemsPerPage);
    }

    return query.getResultList();
}
 
Example 16
Source File: JPAGroupDAO.java    From syncope with Apache License 2.0 5 votes vote down vote up
private List<ADynGroupMembership> findWithADynMemberships(final AnyType anyType) {
    TypedQuery<ADynGroupMembership> query = entityManager().createQuery(
            "SELECT e FROM " + JPAADynGroupMembership.class.getSimpleName() + " e  WHERE e.anyType=:anyType",
            ADynGroupMembership.class);
    query.setParameter("anyType", anyType);
    return query.getResultList();
}
 
Example 17
Source File: LoginDaoImpl.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@Transactional
@Cacheable("users")
@Override
public List<Login> getusers() {
	//EntityManager entityManagerFactory = entityManagerFactory.createEntityManager();
	String qlString = "SELECT l FROM Login l";
	TypedQuery<Login> query = entityManagerFactory.createQuery(qlString, Login.class);	
	List<Login> login = query.getResultList();
	
	return login;
}
 
Example 18
Source File: LocalStorageCapacityRecalculator.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Transactional
public LocalStorageCapacityRecalculator calculateTotalCapacity(String psUuid) {
    final long totalCapacity;
    final long availableCapacity;
    final long totalPhysicalCapacity;
    final long availablePhysicalCapacity;

    String sql = "select sum(ref.totalCapacity)," +
            " sum(ref.availableCapacity)," +
            " sum(ref.totalPhysicalCapacity)," +
            " sum(ref.availablePhysicalCapacity)" +
            " from LocalStorageHostRefVO ref" +
            " where ref.primaryStorageUuid = :psUuid" +
            " group by ref.primaryStorageUuid";
    TypedQuery<Tuple> q = dbf.getEntityManager().createQuery(sql, Tuple.class);
    q.setParameter("psUuid", psUuid);
    List<Tuple> resultList =  q.getResultList();

    if (resultList != null && !resultList.isEmpty()) {
        Tuple ts = resultList.get(0);
        totalCapacity = ts.get(0) == null ? 0 : ts.get(0, Long.class);
        availableCapacity = ts.get(1) == null ? 0 : ts.get(1, Long.class);
        totalPhysicalCapacity = ts.get(2) == null ? 0 : ts.get(2, Long.class);
        availablePhysicalCapacity = ts.get(3) == null ? 0 : ts.get(3, Long.class);
    } else {
        // LocalStorage not mounted
        // Cluster no host
        totalCapacity = 0;
        totalPhysicalCapacity = 0;
        availablePhysicalCapacity = 0;

        Long used = SQL.New("select sum(ref.size)" +
                " from LocalStorageResourceRefVO ref" +
                " where ref.primaryStorageUuid = :psUuid")
                .param("psUuid", psUuid).find();

        availableCapacity = used != null ? totalCapacity - used : 0;
    }

    PrimaryStorageCapacityUpdater pupdater = new PrimaryStorageCapacityUpdater(psUuid);
    pupdater.run(new PrimaryStorageCapacityUpdaterRunnable() {
        @Override
        public PrimaryStorageCapacityVO call(PrimaryStorageCapacityVO cap) {
            cap.setTotalCapacity(totalCapacity);
            cap.setAvailableCapacity(availableCapacity);
            cap.setTotalPhysicalCapacity(totalPhysicalCapacity);
            cap.setAvailablePhysicalCapacity(availablePhysicalCapacity);
            return cap;
        }
    });

    return this;
}
 
Example 19
Source File: RoomDao.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
public List<Room> getGroupRooms(long groupId) {
	TypedQuery<Room> q = em.createNamedQuery("getGroupRooms", Room.class);
	q.setParameter("groupId", groupId);
	return q.getResultList();
}
 
Example 20
Source File: JPAReportTemplateDAO.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Override
public List<ReportTemplate> findAll() {
    TypedQuery<ReportTemplate> query = entityManager().createQuery(
            "SELECT e FROM " + JPAReportTemplate.class.getSimpleName() + " e", ReportTemplate.class);
    return query.getResultList();
}