Example usage for org.hibernate SQLQuery uniqueResult

List of usage examples for org.hibernate SQLQuery uniqueResult

Introduction

In this page you can find the example usage for org.hibernate SQLQuery uniqueResult.

Prototype

R uniqueResult();

Source Link

Document

Convenience method to return a single instance that matches the query, or null if the query returns no results.

Usage

From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java

License:Apache License

public Long latestModificationRunByPipeline(final CaseInsensitiveString pipelineName, final Material material) {
    final long materialId = findMaterialInstance(material).getId();
    String key = cacheKeyForLatestPmrForPipelineKey(materialId, pipelineName.toLower());
    Long modificationId = (Long) goCache.get(key);
    if (modificationId == null) {
        synchronized (key) {
            modificationId = (Long) goCache.get(key);
            if (modificationId == null) {
                modificationId = (Long) getHibernateTemplate().execute((HibernateCallback) session -> {
                    SQLQuery sqlQuery = session.createSQLQuery("SELECT  MAX(pmr.toRevisionId) toRevisionId "
                            + "FROM (SELECT torevisionid, pipelineid FROM pipelineMaterialRevisions WHERE materialid = :material_id)  AS pmr\n"
                            + "INNER JOIN pipelines p ON ( p.name = :pipeline_name AND p.id = pmr.pipelineId)");

                    sqlQuery.setParameter("material_id", materialId);
                    sqlQuery.setParameter("pipeline_name", pipelineName.toString());
                    sqlQuery.addScalar("toRevisionId", new LongType());
                    return sqlQuery.uniqueResult();
                });// w  ww.  ja  va2  s. c o  m
                if (modificationId == null) {
                    modificationId = -1L;
                }
                goCache.put(key, modificationId);
            }
        }
    }
    return modificationId;
}

From source file:com.thoughtworks.go.server.persistence.MaterialRepositoryWithH2IntegrationTest.java

License:Apache License

@Test
@RunIf(value = DatabaseChecker.class, arguments = { DatabaseChecker.H2 })
public void materialFingerprintShouldUseTheHashAlgoritmInMigration47() throws Exception {
    final HgMaterial material = new HgMaterial("url", null);
    byte[] fingerprint = (byte[]) repo.getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            String pattern = format("'type=%s%surl=%s'", material.getType(),
                    AbstractMaterial.FINGERPRINT_DELIMITER, material.getUrl());
            SQLQuery query = session
                    .createSQLQuery(format("CALL HASH('SHA256', STRINGTOUTF8(%s), 1)", pattern));
            return query.uniqueResult();
        }//from   ww  w .  j ava2  s . c o  m
    });
    assertThat(Hex.encodeHexString(fingerprint), is(material.getFingerprint()));
}

From source file:com.tysanclan.site.projectewok.util.forum.AbstractForumViewContext.java

License:Open Source License

protected final int count(SQLQuery query) {
    return ((Number) query.uniqueResult()).intValue();
}

From source file:com.userweave.dao.impl.TestResultDaoImpl.java

License:Open Source License

@Override
public int getValidResultCount(U configuration, FilterFunctor filterFunctor) {
    SurveyExecutionDependentQuery query = new SurveyExecutionDependentQuery("se", "id");

    // query for number of questionnaire results
    QueryEntity result = new QueryEntity(getEntityResultName(), "result");
    query.addQueryEntity(result);//from ww w  .  j  a v  a 2s  .  co m
    query.setResult("count(se.id)");

    // result must match configuration
    query.addAndCondition(PropertyCondition.equals("result.configuration_id", configuration.getId()));

    // join on survey execution for filtering
    query.addLeftJoin(new Join("surveyexecution", "se", "result.surveyexecution_id", "se.id"));

    // only count started or completed surveys
    query.addAndCondition(PropertyCondition.greaterOrEqual("se.state", SurveyExecutionState.STARTED.ordinal()));

    if (filterFunctor != null) {
        filterFunctor.apply(query);
    }

    if (query.getHasGroupBy()) {
        query.setGroupBy("se.id");

        SQLQuery q = new QueryTemplate(query).createSqlQuery(getCurrentSession());

        return q.list().size();
    } else {
        SQLQuery q = new QueryTemplate(query).createSqlQuery(getCurrentSession());

        return ((BigInteger) q.uniqueResult()).intValue();
    }
}

From source file:com.userweave.module.methoden.questionnaire.dao.AnswerDaoImpl.java

License:Open Source License

@Override
public Long getGroupedValidAnswersForMultipleRatingQuestion(MultipleRatingQuestion question,
        FilterFunctor filterFunctor) {//from  w ww  .  jav a2 s.  c o m
    QueryObject query = getQueryObject(question, filterFunctor, "singleratinganswer", "singleratinganswer");

    query.setResult("count(distinct r_qa.surveyexecution_id)");

    SQLQuery q = new QueryTemplate(query).createSqlQuery(getCurrentSession());

    if (query.getHasGroupBy()) {
        return ((Integer) q.list().size()).longValue();
    }

    return ((BigInteger) q.uniqueResult()).longValue();
}

From source file:com.userweave.module.methoden.questionnaire.dao.AnswerDaoImpl.java

License:Open Source License

@Override
public Long getGroupedValidAnswersForDimensionQuestion(DimensionsQuestion question,
        FilterFunctor filterFunctor) {/*from   w w  w .j  a  v  a 2s. c  om*/
    QueryObject query = getQueryObject(question, filterFunctor, "singledimensionanswer",
            "singledimensionanswer");

    query.setResult("count(distinct r_qa.surveyexecution_id)");

    SQLQuery q = new QueryTemplate(query).createSqlQuery(getCurrentSession());

    if (query.getHasGroupBy()) {
        return ((Integer) q.list().size()).longValue();
    }

    return ((BigInteger) q.uniqueResult()).longValue();
}

From source file:com.vertec.daoimpl.InvoiceDAOImpl.java

/**
 * call from InvoiceController--> case "ToPrint"
 *
 * @return/* w  w w . j  a  v  a2  s  .c  om*/
 */
public Object[] getLastInvoice() {

    Session session = NewHibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();

    if (session != null) {
        try {

            SQLQuery query = session
                    .createSQLQuery("SELECT i.invoice_id,i.invoiced_date,c.customer_name,i.tot_after_discount "
                            + "FROM invoice i inner join customer c on i.customer_id=c.customer_id\n"
                            + "ORDER BY invoice_id DESC LIMIT 1;");
            Object[] invoice = (Object[]) query.uniqueResult();
            return invoice;

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }
    return null;

}

From source file:com.vertec.daoimpl.ReportDAOImpl.java

public Object[] invoiceHeaderToReport(int invoiceId) {
    Session session = NewHibernateUtil.getSessionFactory().openSession();
    org.hibernate.Transaction transaction = session.beginTransaction();

    if (session != null) {
        try {/*from  w  ww.j a  v  a2  s .  c o  m*/

            SQLQuery query = session.createSQLQuery(
                    "SELECT i.invoice_id,i.invoiced_date,i.invoice_total,i.discount,i.tot_after_discount,c.customer_name,c.address as cadd,b.address as badd,b.contact_no,sum(i.tot_after_discount-(i.invoice_total-i.discount)) as tax\n"
                            + "FROM invoice i inner join customer c on i.customer_id=c.customer_id inner join branch b on i.branch_id=b.branch_id\n"
                            + "where i.invoice_id=:invoiceId");
            query.setParameter("invoiceId", invoiceId);
            Object[] invoice = (Object[]) query.uniqueResult();
            return invoice;

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }
    return null;
}

From source file:com.vertec.daoimpl.ReportDAOImpl.java

public int getLastInvoiceId() {
    Session session = NewHibernateUtil.getSessionFactory().openSession();
    org.hibernate.Transaction transaction = session.beginTransaction();

    if (session != null) {
        try {/*from ww w .java  2 s.co m*/

            SQLQuery query = session.createSQLQuery(
                    "SELECT invoice_id FROM invoice\n" + "ORDER BY invoice_id DESC\n" + "LIMIT 1;");
            int inId = (Integer) query.uniqueResult();
            return inId;

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }
    return 0;
}

From source file:com.vertec.util.CheckAuth.java

public Object[] checkUserAuth(String code, int gId) {
    Session session = NewHibernateUtil.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    if (session != null) {
        try {/*from w ww .j  a v a 2 s  . com*/

            SQLQuery query = session.createSQLQuery(
                    "SELECT ugpi_id, user_group_id,privilege_item_code FROM user_group_privilege_item inner join privilege_item on user_group_privilege_item.privilege_item_id=privilege_item.privilege_item_id where user_group_privilege_item.user_group_id=:groupId and privilege_item.privilege_item_code=:itemCode");

            query.setParameter("groupId", gId);
            query.setParameter("itemCode", code);
            Object[] ob = (Object[]) query.uniqueResult();

            return ob;

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    return null;
}