Example usage for javax.persistence Query getSingleResult

List of usage examples for javax.persistence Query getSingleResult

Introduction

In this page you can find the example usage for javax.persistence Query getSingleResult.

Prototype

Object getSingleResult();

Source Link

Document

Execute a SELECT query that returns a single untyped result.

Usage

From source file:me.doshou.admin.monitor.web.controller.JPAQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/ql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("ql") String ql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    try {/*  w w  w .j a  va2  s.co m*/
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {
                //1?ql
                try {
                    Query query = em.createQuery(ql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                    return null;
                } catch (Exception e) {
                }
                //2 ?ql
                String findQL = ql;
                String alias = QueryUtils.detectAlias(findQL);
                if (StringUtils.isEmpty(alias)) {
                    Pattern pattern = Pattern.compile("^(.*\\s*from\\s+)(.*)(\\s*.*)",
                            Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
                    findQL = pattern.matcher(findQL).replaceFirst("$1$2 o $3");
                }
                String countQL = QueryUtils.createCountQueryFor(findQL);
                Query countQuery = em.createQuery(countQL);
                Query findQuery = em.createQuery(findQL);
                findQuery.setFirstResult(pageable.getOffset());
                findQuery.setMaxResults(pageable.getPageSize());

                Page page = new PageImpl(findQuery.getResultList(), pageable,
                        (Long) countQuery.getSingleResult());

                model.addAttribute("resultPage", page);
                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showQLForm();
}

From source file:mx.edu.ittepic.proyectofinal.ejbs.ejbUsers.java

public String checkPass(String username, String password) {

    Message m = new Message();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();//  w w  w  . jav  a  2s .co  m

    try {
        Users user;
        Query q = entity.createNamedQuery("Users.check").setParameter("username", username)
                .setParameter("password", password);

        user = (Users) q.getSingleResult();

        m.setCode(200);
        m.setMsg("El usuario y la contrasea son correctos");
        m.setDetail("OK");

    } catch (NoResultException e) {
        m.setCode(208);
        m.setMsg("Usuario o contrasea incorrectos");
        m.setDetail(e.toString());
    } catch (StackOverflowError e) {
        m.setCode(200);
        m.setMsg("El usuario y la contrasea son correctos");
        m.setDetail("OK");
    }
    return gson.toJson(m);
}

From source file:corner.orm.gae.impl.PaginatedJapEntityService.java

License:asdf

public long count(final Class<?> persistClass, final Object conditions) {
    return (Long) this.template.execute(new JpaCallback() {
        @Override// w  ww. j  a v  a2  s . co  m
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            Iterable con = typeCoercer.coerce(conditions, Iterable.class);
            final Iterator it = con == null ? null : con.iterator();
            final StringBuffer sb = buildConditionJPQL(persistClass, it);
            sb.insert(0, "select count(root) ");
            Query query = entityManager.createQuery(sb.toString());
            if (it != null) {
                int i = 0;
                while (it.hasNext()) {
                    query.setParameter(i++, it.next());
                }
            }
            return Long.parseLong(query.getSingleResult().toString());
        }
    });
}

From source file:com.assetmanager.service.auth.UserDetailsServiceImpl.java

/**
 * Indicates if the activation e-mail has been sent.
 *
 * @param username the username//from   w  w  w . j  a va  2s  .co  m
 * @return true if sent; false otherwise
 */
@Override
public final boolean isActivationEmailSent(final String username) {
    UserAccount user = (UserAccount) memcacheService.get(username);

    if (user == null) {
        final Query query = entityManager.createQuery(SELECT_USER);
        query.setParameter(USERNAME, username);

        try {
            user = (UserAccount) query.getSingleResult();

            memcacheService.put(username, user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
        } catch (NoResultException e) {
            throw new UsernameNotFoundException("Username not found.", e);
        }
    }

    return user.isActivationEmailSent();
}

From source file:com.exp.tracker.services.impl.JasperReportGenerationService.java

@Transactional(readOnly = true)
public byte[] getReportForSettlement(Long sid, String reportName) {
    Query queryGetReport = em.createNamedQuery("getReport");
    queryGetReport.setParameter("sid", sid);
    queryGetReport.setParameter("reportName", reportName);
    ReportEntity re = (ReportEntity) queryGetReport.getSingleResult();
    return re.getReportContent();
}

From source file:com.telefonica.euro_iaas.sdc.dao.impl.ProductInstanceDaoJpaImpl.java

public ProductInstance loadWithArtifacts(String productInstanceName) throws EntityNotFoundException {

    Query query = (Query) getEntityManager()
            .createQuery("select p from ProductInstance p left join fetch p.artifact where p.name = '"
                    + productInstanceName + "'");

    ProductInstance productInstance = null;
    try {/*from w  w w  .j  ava 2 s.c  om*/
        productInstance = (ProductInstance) query.getSingleResult();
    } catch (NoResultException e) {
        String message = " No ProductInstance found in the database " + "with name: " + productInstanceName;
        System.out.println(message);
        throw new EntityNotFoundException(ProductInstance.class, "name", productInstanceName);
    }
    return productInstance;
}

From source file:com.assetmanager.service.auth.UserDetailsServiceImpl.java

/**
 * Updates the activation e-mail sent status.
 *
 * @param username the username//from  www .jav a 2s.co  m
 */
@Override
@Transactional
public final void activationEmailSent(final String username) {
    final Query query = entityManager.createQuery(SELECT_USER);
    query.setParameter(USERNAME, username);

    try {
        final UserAccount user = (UserAccount) query.getSingleResult();
        user.setActivationEmailSent(true);

        entityManager.persist(user);

        memcacheService.put(user.getUsername(), user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
    } catch (NoResultException e) {
        throw new UsernameNotFoundException("Username not found.", e);
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.dao.impl.SubNetworkInstanceDaoJpaImpl.java

private SubNetworkInstance findByNetworkInstanceName(String name, String vdc, String region)
        throws EntityNotFoundException {
    Query query = getEntityManager().createQuery(
            "select p from SubNetworkInstance p where p.name = :name and p.vdc = :vdc and p.region = :region");
    query.setParameter("name", name);
    query.setParameter("vdc", vdc);
    query.setParameter("region", region);
    SubNetworkInstance subNetworkInstance = null;
    try {//from  w w w.j a v a2s. co m
        subNetworkInstance = (SubNetworkInstance) query.getSingleResult();
    } catch (NoResultException e) {
        String message = " No subNetworkInstance found in the database with id: " + name + " Exception: "
                + e.getMessage();
        throw new EntityNotFoundException(NetworkInstance.class, "name", name);
    }
    return subNetworkInstance;
}

From source file:DAO.PersonnesDAOImpl.java

@Transactional(readOnly = true)
@Override//  w  ww  .  j a  v  a2s .  co m
public PersonnesEntity findByLogin(String login) {
    Query q = em.createQuery("SELECT p FROM PersonnesEntity p " + "WHERE p.login = ?");
    q.setParameter(1, login);
    PersonnesEntity p = null;
    if (q.getResultList().size() == 1) {
        p = (PersonnesEntity) q.getSingleResult();
    }
    return p;
}

From source file:be.fedict.trust.service.dao.bean.TrustDomainDAOBean.java

/**
 * {@inheritDoc}/*from w w  w .ja  va  2 s  . c o  m*/
 */
public TrustDomainEntity getDefaultTrustDomain() {

    LOG.debug("return the default trust domain");
    Query query = this.entityManager.createNamedQuery(TrustDomainEntity.QUERY_GET_DEFAULT);
    return (TrustDomainEntity) query.getSingleResult();
}