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

The following examples show how to use javax.persistence.TypedQuery#setParameter() . 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: 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 2
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) {
    TypedQuery<UserEntity> query = em.createNamedQuery("groupMembership", UserEntity.class);
    query.setParameter("groupId", group.getId());
    if (firstResult != -1) {
        query.setFirstResult(firstResult);
    }
    if (maxResults != -1) {
        query.setMaxResults(maxResults);
    }
    List<UserEntity> results = query.getResultList();

    List<UserModel> users = new LinkedList<>();
    for (UserEntity user : results) {
        users.add(new UserAdapter(session, realm, em, user));
    }
    return users;
}
 
Example 3
Source File: TicketPriceEndpoint.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<TicketPrice> findByIdQuery = em.createQuery("SELECT DISTINCT t FROM TicketPrice t LEFT JOIN FETCH t.show LEFT JOIN FETCH t.section LEFT JOIN FETCH t.ticketCategory WHERE t.id = :entityId ORDER BY t.id", TicketPrice.class);
   findByIdQuery.setParameter("entityId", id);
   TicketPrice entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   TicketPriceDTO dto = new TicketPriceDTO(entity);
   return Response.ok(dto).build();
}
 
Example 4
Source File: NodeTemplateInstanceRepository.java    From container with Apache License 2.0 6 votes vote down vote up
public Collection<NodeTemplateInstance> findByTemplateId(final String templateId) {
    try (AutoCloseableEntityManager em = EntityManagerProvider.createEntityManager()) {
        final CriteriaBuilder cb = em.getCriteriaBuilder();

        final ParameterExpression<String> templateIdParameter = cb.parameter(String.class);

        final CriteriaQuery<NodeTemplateInstance> cq = cb.createQuery(NodeTemplateInstance.class);
        final Root<NodeTemplateInstance> sti = cq.from(NodeTemplateInstance.class);
        cq.select(sti).where(cb.equal(sti.get("templateId"), templateIdParameter));

        final TypedQuery<NodeTemplateInstance> q = em.createQuery(cq);
        q.setParameter(templateIdParameter, templateId);

        return q.getResultList();
    }
}
 
Example 5
Source File: InstanceOfferingCascadeExtension.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
private List<InstanceOfferingInventory> getForAccount(List<AccountInventory> invs) {
    List<String> accountUuids = CollectionUtils.transformToList(invs, new Function<String, AccountInventory>() {
        @Override
        public String call(AccountInventory arg) {
            return arg.getUuid();
        }
    });

    String sql = "select d from InstanceOfferingVO d, AccountResourceRefVO r where d.uuid = r.resourceUuid and" +
            " r.resourceType = :rtype and r.accountUuid in (:auuids)";
    TypedQuery<InstanceOfferingVO> q = dbf.getEntityManager().createQuery(sql, InstanceOfferingVO.class);
    q.setParameter("rtype", InstanceOfferingVO.class.getSimpleName());
    q.setParameter("auuids", accountUuids);
    List<InstanceOfferingVO> vos = q.getResultList();
    return InstanceOfferingInventory.valueOf(vos);
}
 
Example 6
Source File: CoreCapabilityServiceImpl.java    From container with Apache License 2.0 6 votes vote down vote up
@Override
/**
 * {@inheritDoc}
 */
public List<String> getCapabilities(final String providerName, final ProviderType providerType) {
    LOG.debug("Getting \"{}\" capabilities of \"{}\"...", providerType, providerName);
    em.getTransaction().begin();

    TypedQuery<Capability> query = em.createNamedQuery(Capability.byProvider, Capability.class);
    query.setParameter("providerType", providerType);
    query.setParameter("providerName", providerName);

    final List<String> capabilities = query.getResultList().stream()
        .map(Capability::getCapability).collect(Collectors.toList());

    LOG.debug("Getting \"{}\" capabilities of \"{}\" successfully completed.", providerType, providerName);
    em.getTransaction().commit();
    return capabilities;
}
 
Example 7
Source File: JpaUserProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public UserModel getServiceAccount(ClientModel client) {
    TypedQuery<UserEntity> query = em.createNamedQuery("getRealmUserByServiceAccount", UserEntity.class);
    query.setParameter("realmId", client.getRealm().getId());
    query.setParameter("clientInternalId", client.getId());
    List<UserEntity> results = query.getResultList();
    if (results.isEmpty()) {
        return null;
    } else if (results.size() > 1) {
        throw new IllegalStateException("More service account linked users found for client=" + client.getClientId() +
                ", results=" + results);
    } else {
        UserEntity user = results.get(0);
        return new UserAdapter(session, client.getRealm(), em, user);
    }
}
 
Example 8
Source File: EipManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Transactional
private void changeEipOwner(AccountResourceRefInventory ref, String newOwnerUuid) {
    String sql = "select eip.uuid" +
            " from VmInstanceVO vm, VmNicVO nic, EipVO eip" +
            " where vm.uuid = nic.vmInstanceUuid" +
            " and nic.uuid = eip.vmNicUuid" +
            " and vm.uuid = :uuid";
    TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
    q.setParameter("uuid", ref.getResourceUuid());
    List<String> eipUuids = q.getResultList();
    if (eipUuids.isEmpty()) {
        logger.debug(String.format("Vm[uuid:%s] doesn't have any eip, there is no need to change owner of eip.",
                ref.getResourceUuid()));
        return;
    }

    for (String uuid : eipUuids) {
        acntMgr.changeResourceOwner(uuid, newOwnerUuid);
    }
}
 
Example 9
Source File: NestedTicketDTO.java    From monolith with Apache License 2.0 6 votes vote down vote up
public Ticket fromDTO(Ticket entity, EntityManager em)
{
   if (entity == null)
   {
      entity = new Ticket();
   }
   if (this.id != null)
   {
      TypedQuery<Ticket> findByIdQuery = em.createQuery(
            "SELECT DISTINCT t FROM Ticket t WHERE t.id = :entityId",
            Ticket.class);
      findByIdQuery.setParameter("entityId", this.id);
      try
      {
         entity = findByIdQuery.getSingleResult();
      }
      catch (javax.persistence.NoResultException nre)
      {
         entity = null;
      }
      return entity;
   }
   entity = em.merge(entity);
   return entity;
}
 
Example 10
Source File: EventCategoryEndpoint.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<EventCategory> findByIdQuery = em.createQuery("SELECT DISTINCT e FROM EventCategory e WHERE e.id = :entityId ORDER BY e.id", EventCategory.class);
   findByIdQuery.setParameter("entityId", id);
   EventCategory entity;
   try
   {
      entity = findByIdQuery.getSingleResult();
   }
   catch (NoResultException nre)
   {
      entity = null;
   }
   if (entity == null)
   {
      return Response.status(Status.NOT_FOUND).build();
   }
   EventCategoryDTO dto = new EventCategoryDTO(entity);
   return Response.ok(dto).build();
}
 
Example 11
Source File: InventoryDaoImpl.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
@Override
public Catalog getProduct(Integer id) {
	EntityManager em = entityManagerInventory.createEntityManager();
	String qlString = "SELECT c FROM Catalog c WHERE c.id = ?1";
	TypedQuery<Catalog> query = em.createQuery(qlString, Catalog.class);		
	query.setParameter(1, id);
	return query.getSingleResult();
	
}
 
Example 12
Source File: PartitionDaoImpl.java    From metacat with Apache License 2.0 5 votes vote down vote up
@Override
public List<Partition> getByUris(final List<String> uris, final boolean prefixSearch) {
    TypedQuery<Partition> query = null;
    if (prefixSearch) {
        final StringBuilder builder = new StringBuilder("select p from Partition p where 1=2");
        uris.forEach(uri -> builder.append(" or uri like '").append(uri).append("%'"));
        query = em.get().createQuery(builder.toString(), Partition.class);
    } else {
        query = em.get().createNamedQuery(Partition.NAME_QUERY_GET_BY_URI, Partition.class);
        query.setParameter("uris", uris);
    }
    return query.getResultList();
}
 
Example 13
Source File: JpaPersonConverter.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
private JpaPerson createEntity(Person source) {
    JpaPerson converted = null;
    if (source != null) {
        TypedQuery<JpaPerson> query = manager.createNamedQuery(JpaPerson.FIND_BY_USERNAME, JpaPerson.class);
        query.setParameter(JpaPerson.USERNAME_PARAM, source.getUsername());
        converted = getSingleResult(query.getResultList());

        if (converted == null) {
            converted = new JpaPerson();
        }
        updateProperties(source, converted);
    }
    return converted;
}
 
Example 14
Source File: CephBackupStorageBase.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private boolean canDelete(String installPath) {
    String sql = "select count(c) from ImageBackupStorageRefVO img, ImageCacheVO c where img.imageUuid = c.imageUuid and img.backupStorageUuid = :bsUuid and img.installPath = :installPath";
    TypedQuery<Long> q = dbf.getEntityManager().createQuery(sql, Long.class);
    q.setParameter("bsUuid", self.getUuid());
    q.setParameter("installPath", installPath);
    return q.getSingleResult() == 0;
}
 
Example 15
Source File: BackupStorageSelectPrimaryStorageAllocatorFlow.java    From zstack with Apache License 2.0 5 votes vote down vote up
@Transactional(readOnly = true)
private List<HostVO> findHostsByPrimaryStorageTypes(List<String> psTypes) {
    String sql = "select distinct h" +
            " from HostVO h, PrimaryStorageClusterRefVO ref, PrimaryStorageVO ps" +
            " where ref.clusterUuid = h.clusterUuid" +
            " and ref.primaryStorageUuid = ps.uuid" +
            " and ps.type in (:psTypes)" +
            " and h.uuid in (:huuids)";

    TypedQuery<HostVO> q = dbf.getEntityManager().createQuery(sql, HostVO.class);
    q.setParameter("psTypes", psTypes);
    q.setParameter("huuids", getHostUuidsFromCandidates());

    return q.getResultList();
}
 
Example 16
Source File: UserRepository.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * Return the user with the name.
 * @param userName The user name.
 * @return User or null if the user doesn't exist.
 */
public PersistenceUser getUserByName(String userName) {
	EntityManager em = getEM();
	TypedQuery<PersistenceUser> allMatchesQuery =
			em.createQuery("SELECT u FROM " + getEntityClass().getName()
					+ " u WHERE u.userName = :name", getEntityClass())
			.setMaxResults(1);
	allMatchesQuery.setParameter("name", userName);
	List<PersistenceUser> entities = allMatchesQuery.getResultList();
	if (entities == null || entities.isEmpty()) {
		return null;
	}
	return entities.get(0);
}
 
Example 17
Source File: KVMHost.java    From zstack with Apache License 2.0 5 votes vote down vote up
private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) {
    String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)";
    TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class);
    query.setParameter("l3NetworkUuid", l3NetworkUuid);
    L2NetworkVO l2vo = query.getSingleResult();
    return L2NetworkInventory.valueOf(l2vo);
}
 
Example 18
Source File: JpaBenchmark.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void findByTitleCriteria(Blackhole sink) {

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Book> q = cb.createQuery(Book.class);
	Root<Book> c = q.from(Book.class);

	ParameterExpression<String> parameter = cb.parameter(String.class);

	TypedQuery<Book> query = em.createQuery(q.select(c).where(cb.equal(c.get("title"), parameter)));
	query.setParameter(parameter, "title0");

	sink.consume(query.getSingleResult());
}
 
Example 19
Source File: JpaRealmProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Set<RoleModel> searchForClientRoles(RealmModel realm, ClientModel client, String search, Integer first, Integer max) {
    TypedQuery<RoleEntity> query = em.createNamedQuery("searchForClientRoles", RoleEntity.class);
    query.setParameter("client", client.getId());
    return searchForRoles(query, realm, search, first, max);
}
 
Example 20
Source File: QueryTypesExamples.java    From tutorials with MIT License 4 votes vote down vote up
public UserEntity getUserByIdWithTypedQuery(Long id) {
    TypedQuery<UserEntity> typedQuery = getEntityManager().createQuery("SELECT u FROM UserEntity u WHERE u.id=:id", UserEntity.class);
    typedQuery.setParameter("id", id);
    return typedQuery.getSingleResult();
}