Search in sources :

Example 46 with Query

use of org.hibernate.query.Query in project dhis2-core by dhis2.

the class HibernateGenericStore method getAllByAttributes.

@Override
public List<T> getAllByAttributes(List<Attribute> attributes) {
    CriteriaBuilder builder = getCriteriaBuilder();
    CriteriaQuery<T> query = builder.createQuery(getClazz());
    Root<T> root = query.from(getClazz());
    query.select(root).distinct(true);
    List<Predicate> predicates = attributes.stream().map(attribute -> builder.isNotNull(builder.function(FUNCTION_JSONB_EXTRACT_PATH, String.class, root.get("attributeValues"), builder.literal(attribute.getUid())))).collect(Collectors.toList());
    query.where(builder.or(predicates.toArray(new Predicate[predicates.size()])));
    return getSession().createQuery(query).list();
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) AttributeValue(org.hisp.dhis.attribute.AttributeValue) Criteria(org.hibernate.Criteria) JsonAttributeValueBinaryType(org.hisp.dhis.hibernate.jsonb.type.JsonAttributeValueBinaryType) Session(org.hibernate.Session) Function(java.util.function.Function) TypedQuery(javax.persistence.TypedQuery) ObjectDeletionRequestedEvent(org.hisp.dhis.common.ObjectDeletionRequestedEvent) Attribute(org.hisp.dhis.attribute.Attribute) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) GenericStore(org.hisp.dhis.common.GenericStore) NonUniqueResultException(javax.persistence.NonUniqueResultException) Lists(com.google.common.collect.Lists) Predicate(javax.persistence.criteria.Predicate) NativeQuery(org.hibernate.query.NativeQuery) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Query(org.hibernate.query.Query) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) Expression(javax.persistence.criteria.Expression) Root(javax.persistence.criteria.Root) AuditLogUtil(org.hisp.dhis.common.AuditLogUtil) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) SessionFactory(org.hibernate.SessionFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) QueryHints(org.hibernate.annotations.QueryHints) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) Order(javax.persistence.criteria.Order) Predicate(javax.persistence.criteria.Predicate)

Example 47 with Query

use of org.hibernate.query.Query in project dhis2-core by dhis2.

the class HibernateGenericStore method countAllValuesByAttributes.

@Override
public long countAllValuesByAttributes(List<Attribute> attributes) {
    CriteriaBuilder builder = getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);
    Root<T> root = query.from(getClazz());
    query.select(builder.countDistinct(root));
    List<Predicate> predicates = attributes.stream().map(attribute -> builder.isNotNull(builder.function(FUNCTION_JSONB_EXTRACT_PATH, String.class, root.get("attributeValues"), builder.literal(attribute.getUid())))).collect(Collectors.toList());
    query.where(builder.or(predicates.toArray(new Predicate[predicates.size()])));
    return getSession().createQuery(query).getSingleResult();
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) AttributeValue(org.hisp.dhis.attribute.AttributeValue) Criteria(org.hibernate.Criteria) JsonAttributeValueBinaryType(org.hisp.dhis.hibernate.jsonb.type.JsonAttributeValueBinaryType) Session(org.hibernate.Session) Function(java.util.function.Function) TypedQuery(javax.persistence.TypedQuery) ObjectDeletionRequestedEvent(org.hisp.dhis.common.ObjectDeletionRequestedEvent) Attribute(org.hisp.dhis.attribute.Attribute) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) GenericStore(org.hisp.dhis.common.GenericStore) NonUniqueResultException(javax.persistence.NonUniqueResultException) Lists(com.google.common.collect.Lists) Predicate(javax.persistence.criteria.Predicate) NativeQuery(org.hibernate.query.NativeQuery) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Query(org.hibernate.query.Query) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) Expression(javax.persistence.criteria.Expression) Root(javax.persistence.criteria.Root) AuditLogUtil(org.hisp.dhis.common.AuditLogUtil) IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) SessionFactory(org.hibernate.SessionFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) QueryHints(org.hibernate.annotations.QueryHints) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) Order(javax.persistence.criteria.Order) Predicate(javax.persistence.criteria.Predicate)

Example 48 with Query

use of org.hibernate.query.Query in project midpoint by Evolveum.

the class AbstractOrgClosureTest method _test110ScanOrgStructure.

protected void _test110ScanOrgStructure() throws Exception {
    OperationResult opResult = new OperationResult("===[ test110ScanOrgStructure ]===");
    long start = System.currentTimeMillis();
    scanOrgStructure(opResult);
    System.out.println("Found " + allOrgCreated.size() + " orgs and " + (objectCount - allOrgCreated.size()) + " users in " + (System.currentTimeMillis() - start) + " ms");
    try (Session session = openSession()) {
        Query q = session.createNativeQuery("select count(*) from m_org_closure");
        System.out.println("OrgClosure table has " + q.list().get(0) + " rows");
        closureSize = Long.parseLong(q.list().get(0).toString());
    }
}
Also used : Query(org.hibernate.query.Query) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Session(org.hibernate.Session)

Example 49 with Query

use of org.hibernate.query.Query in project midpoint by Evolveum.

the class AbstractOrgClosureTest method checkClosureMatrix.

protected boolean checkClosureMatrix() throws SchemaException {
    try (Session session = openSession()) {
        // we compute the closure table "by hand" as 1 + A + A^2 + A^3 + ... + A^n where n is the greatest expected path length
        int vertices = getVertices().size();
        long start = System.currentTimeMillis();
        // used to give indices to vertices
        List<String> vertexList = new ArrayList<>(getVertices());
        if (DUMP_TC_MATRIX_DETAILS) {
            logger.info("Vertex list = {}", vertexList);
        }
        DoubleMatrix2D a = new SparseDoubleMatrix2D(vertices, vertices);
        // }
        for (DefaultEdge edge : orgGraph.edgeSet()) {
            a.set(vertexList.indexOf(orgGraph.getEdgeSource(edge)), vertexList.indexOf(orgGraph.getEdgeTarget(edge)), 1.0);
        }
        DoubleMatrix2D result = new SparseDoubleMatrix2D(vertices, vertices);
        for (int i = 0; i < vertices; i++) {
            result.setQuick(i, i, 1.0);
        }
        DoubleMatrix2D power = result.copy();
        Algebra alg = new Algebra();
        for (int level = 1; level <= maxLevel; level++) {
            power = alg.mult(power, a);
            result.assign(power, Functions.plus);
        // System.out.println("a=" + a);
        // System.out.println("a^"+level+"="+power);
        }
        logger.info("TC matrix computed in {} ms", System.currentTimeMillis() - start);
        if (DUMP_TC_MATRIX_DETAILS) {
            logger.info("TC matrix expected = {}", result);
        }
        Query q = session.createNativeQuery("select descendant_oid, ancestor_oid, val from m_org_closure").addScalar("descendant_oid", StringType.INSTANCE).addScalar("ancestor_oid", StringType.INSTANCE).addScalar("val", LongType.INSTANCE);
        List<Object[]> list = q.list();
        logger.info("OrgClosure has {} rows", list.size());
        DoubleMatrix2D closureInDatabase = new SparseDoubleMatrix2D(vertices, vertices);
        for (Object[] item : list) {
            int val = Integer.parseInt(item[2].toString());
            if (val == 0) {
                throw new IllegalStateException("Row with val == 0 in closure table: " + list);
            }
            closureInDatabase.set(vertexList.indexOf(item[0]), vertexList.indexOf(item[1]), val);
        }
        if (DUMP_TC_MATRIX_DETAILS) {
            logger.info("TC matrix fetched from db = {}", closureInDatabase);
        }
        double zSumResultBefore = result.zSum();
        double zSumClosureInDb = closureInDatabase.zSum();
        result.assign(closureInDatabase, Functions.minus);
        double zSumResultAfter = result.zSum();
        logger.info("Summary of items in closure computed: {}, in DB-stored closure: {}, delta: {}", zSumResultBefore, zSumClosureInDb, zSumResultAfter);
        if (DUMP_TC_MATRIX_DETAILS) {
            logger.info("Difference matrix = {}", result);
        }
        boolean problem = false;
        for (int i = 0; i < vertices; i++) {
            for (int j = 0; j < vertices; j++) {
                double delta = result.get(i, j);
                if (Math.round(delta) != 0) {
                    System.err.println("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta + " (closureInDB=" + closureInDatabase.get(i, j) + ", expected=" + (result.get(i, j) + closureInDatabase.get(i, j)) + ")");
                    logger.error("delta(" + vertexList.get(i) + "," + vertexList.get(j) + ") = " + delta);
                    problem = true;
                }
            }
        }
        if (problem) {
            checkOrgGraph();
        }
        return problem;
    }
}
Also used : Query(org.hibernate.query.Query) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) DefaultEdge(org.jgrapht.graph.DefaultEdge) Algebra(cern.colt.matrix.linalg.Algebra) DoubleMatrix2D(cern.colt.matrix.DoubleMatrix2D) SparseDoubleMatrix2D(cern.colt.matrix.impl.SparseDoubleMatrix2D) PrismObject(com.evolveum.midpoint.prism.PrismObject) SparseDoubleMatrix2D(cern.colt.matrix.impl.SparseDoubleMatrix2D) Session(org.hibernate.Session)

Example 50 with Query

use of org.hibernate.query.Query in project midpoint by Evolveum.

the class AbstractOrgClosureTest method _test400UnloadOrgStructure.

@UnusedTestElement
protected void _test400UnloadOrgStructure() throws Exception {
    OperationResult opResult = new OperationResult("===[ unloadOrgStruct ]===");
    long start = System.currentTimeMillis();
    removeOrgStructure(opResult);
    System.out.println("Removed in " + (System.currentTimeMillis() - start) + " ms");
    try (Session session = openSession()) {
        Query q = session.createNativeQuery("select count(*) from m_org_closure");
        System.out.println("OrgClosure table has " + q.list().get(0) + " rows");
    }
    logger.info("Finish.");
}
Also used : Query(org.hibernate.query.Query) ObjectQuery(com.evolveum.midpoint.prism.query.ObjectQuery) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Session(org.hibernate.Session) UnusedTestElement(com.evolveum.midpoint.tools.testng.UnusedTestElement)

Aggregations

Query (org.hibernate.query.Query)149 Test (org.junit.Test)46 Session (org.hibernate.Session)39 List (java.util.List)24 ArrayList (java.util.ArrayList)19 TestForIssue (org.hibernate.testing.TestForIssue)19 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)17 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)17 HashMap (java.util.HashMap)15 Map (java.util.Map)14 NativeQuery (org.hibernate.query.NativeQuery)14 AbstractJPATest (org.hibernate.test.jpa.AbstractJPATest)11 SessionFactory (org.hibernate.SessionFactory)9 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)7 SQLException (java.sql.SQLException)7 Collectors (java.util.stream.Collectors)7 RQuery (com.evolveum.midpoint.repo.sql.query.RQuery)6 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)6 Predicate (javax.persistence.criteria.Predicate)6 Root (javax.persistence.criteria.Root)6