Search in sources :

Example 11 with CriteriaQuery

use of jakarta.persistence.criteria.CriteriaQuery in project hibernate-orm by hibernate.

the class MultiSelectTests method simpleArrayTest.

@Test
public void simpleArrayTest(SessionFactoryScope scope) {
    scope.inTransaction((session) -> {
        final CriteriaBuilder nodeBuilder = session.getFactory().getNodeBuilder();
        final CriteriaQuery criteria = nodeBuilder.createQuery();
        final Root<BasicEntity> root = criteria.from(BasicEntity.class);
        final EntityType<BasicEntity> model = root.getModel();
        criteria.select(nodeBuilder.array(root.get(model.getDeclaredSingularAttribute("id", Integer.class)), root.get(model.getDeclaredSingularAttribute("data", String.class))));
        final List<Object[]> results = session.createQuery(criteria).list();
        assertThat(results).hasSize(1);
        final Object[] firstResult = results.get(0);
        assertThat(firstResult[0]).isEqualTo(1);
        assertThat(firstResult[1]).isEqualTo("abc");
    });
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) BasicEntity(org.hibernate.testing.orm.domain.gambit.BasicEntity) Test(org.junit.jupiter.api.Test)

Example 12 with CriteriaQuery

use of jakarta.persistence.criteria.CriteriaQuery in project hibernate-orm by hibernate.

the class MultiSelectTests method singleSelectionTupleTest.

@Test
public void singleSelectionTupleTest(SessionFactoryScope scope) {
    scope.inTransaction((session) -> {
        final CriteriaBuilder nodeBuilder = session.getFactory().getNodeBuilder();
        final CriteriaQuery criteria = nodeBuilder.createTupleQuery();
        final Root<BasicEntity> root = criteria.from(BasicEntity.class);
        final EntityType<BasicEntity> model = root.getModel();
        criteria.select(root.get(model.getDeclaredSingularAttribute("id", Integer.class)));
        final List<Tuple> results = session.createQuery(criteria).list();
        assertThat(results).hasSize(1);
        final Tuple firstResult = results.get(0);
        assertThat(firstResult.get(0)).isEqualTo(1);
    });
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) Tuple(jakarta.persistence.Tuple) BasicEntity(org.hibernate.testing.orm.domain.gambit.BasicEntity) Test(org.junit.jupiter.api.Test)

Example 13 with CriteriaQuery

use of jakarta.persistence.criteria.CriteriaQuery in project mycore by MyCoRe-Org.

the class MCRIFSCommands method checkDerivatesWithProjectIDInMCRFSNODES.

@MCRCommand(syntax = "check mcrfsnodes of derivates with project id {0}", help = "check the entries of MCRFSNODES with project ID {0} that the derivate exists")
public static void checkDerivatesWithProjectIDInMCRFSNODES(String projectId) {
    LOGGER.info("Start check of MCRFSNODES for derivates with project ID {}", projectId);
    if (projectId == null || projectId.length() == 0) {
        LOGGER.error("Project ID missed for check MCRFSNODES entries of derivates with project ID {0}");
        return;
    }
    MCRXMLMetadataManager mgr = MCRXMLMetadataManager.instance();
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<String> query = cb.createQuery(String.class);
    Root<MCRFSNODES> nodes = query.from(MCRFSNODES.class);
    AtomicInteger counter = new AtomicInteger();
    em.createQuery(query.distinct(true).select(nodes.get(MCRFSNODES_.owner)).where(cb.like(nodes.get(MCRFSNODES_.owner), projectId + "\\_%"))).getResultList().stream().peek(ignore -> counter.incrementAndGet()).map(MCRObjectID::getInstance).filter(derID -> {
        try {
            return !mgr.exists(derID);
        } catch (MCRPersistenceException e) {
            LOGGER.error("Error while checking existence of {}", derID, e);
            return true;
        }
    }).forEach(missingDerivate -> LOGGER.error("   !!!! Can't find MCRFSNODES entry {} as existing derivate", missingDerivate));
    LOGGER.info("Check done for {} entries", counter.get());
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) Transformer(javax.xml.transform.Transformer) Arrays(java.util.Arrays) Date(java.util.Date) StreamResult(javax.xml.transform.stream.StreamResult) FileTime(java.nio.file.attribute.FileTime) ParameterExpression(jakarta.persistence.criteria.ParameterExpression) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Map(java.util.Map) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRFSNODES(org.mycore.backend.hibernate.tables.MCRFSNODES) MCRFileCollection(org.mycore.datamodel.ifs2.MCRFileCollection) URI(java.net.URI) Method(java.lang.reflect.Method) GregorianCalendar(java.util.GregorianCalendar) TimeZone(java.util.TimeZone) MCRPersistenceException(org.mycore.common.MCRPersistenceException) StandardOpenOption(java.nio.file.StandardOpenOption) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Objects(java.util.Objects) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) MCRUtils(org.mycore.common.MCRUtils) List(java.util.List) Attributes2Impl(org.xml.sax.ext.Attributes2Impl) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) Root(jakarta.persistence.criteria.Root) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRFilesystemNode(org.mycore.datamodel.ifs.MCRFilesystemNode) SAXException(org.xml.sax.SAXException) EntityManager(jakarta.persistence.EntityManager) MCRContentStoreFactory(org.mycore.datamodel.ifs.MCRContentStoreFactory) TypedQuery(jakarta.persistence.TypedQuery) MCRNode(org.mycore.datamodel.ifs2.MCRNode) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) MCRFSNODES_(org.mycore.backend.hibernate.tables.MCRFSNODES_) Charset(java.nio.charset.Charset) MCRDirectory(org.mycore.datamodel.ifs.MCRDirectory) MCRContentStore(org.mycore.datamodel.ifs.MCRContentStore) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) MCRCStoreIFS2(org.mycore.datamodel.ifs2.MCRCStoreIFS2) MCRFile(org.mycore.datamodel.ifs.MCRFile) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) NotDirectoryException(java.nio.file.NotDirectoryException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) OutputKeys(javax.xml.transform.OutputKeys) Field(java.lang.reflect.Field) File(java.io.File) NameFileComparator(org.apache.commons.io.comparator.NameFileComparator) AbstractMap(java.util.AbstractMap) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) TransformerHandler(javax.xml.transform.sax.TransformerHandler) LogManager(org.apache.logging.log4j.LogManager) EntityManager(jakarta.persistence.EntityManager) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MCRXMLMetadataManager(org.mycore.datamodel.common.MCRXMLMetadataManager) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) MCRPersistenceException(org.mycore.common.MCRPersistenceException) MCRFSNODES(org.mycore.backend.hibernate.tables.MCRFSNODES) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 14 with CriteriaQuery

use of jakarta.persistence.criteria.CriteriaQuery in project eclipselink by eclipse-ee4j.

the class JUnitCriteriaSimpleTestSuite method testOneEqualsOne.

/**
 * Tests 1=1 returns correct result.
 */
public void testOneEqualsOne() throws Exception {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        CriteriaBuilder qb = em.getCriteriaBuilder();
        // "SELECT e FROM Employee e"
        Query query = em.createQuery(qb.createQuery(Employee.class));
        List emps = query.getResultList();
        assertNotNull(emps);
        int numRead = emps.size();
        // "SELECT e FROM Employee e WHERE 1=1");
        CriteriaQuery<Employee> cq = qb.createQuery(Employee.class);
        cq.where(qb.equal(qb.literal(1), 1));
        emps = em.createQuery(cq).getResultList();
        assertNotNull(emps);
        assertEquals(numRead, emps.size());
        ExpressionBuilder builder = new ExpressionBuilder();
        query = ((JpaEntityManager) em.getDelegate()).createQuery(builder.value(1).equal(builder.value(1)), Employee.class);
        emps = query.getResultList();
        assertNotNull(emps);
        assertEquals(numRead, emps.size());
    } finally {
        rollbackTransaction(em);
        closeEntityManager(em);
    }
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) TypedQuery(jakarta.persistence.TypedQuery) Query(jakarta.persistence.Query) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) List(java.util.List) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder)

Example 15 with CriteriaQuery

use of jakarta.persistence.criteria.CriteriaQuery in project eclipselink by eclipse-ee4j.

the class JUnitCriteriaSimpleTestSuiteBase method mapCastTest.

public void mapCastTest() {
    EntityManager em = createEntityManager();
    beginTransaction(em);
    try {
        BeerConsumer bc1 = new BeerConsumer();
        bc1.setName("George");
        em.persist(bc1);
        Blue blue = new Blue();
        blue.setUniqueKey(new BigInteger("1"));
        em.persist(blue);
        bc1.addBlueBeerToConsume(blue);
        blue.setBeerConsumer(bc1);
        BeerConsumer bc2 = new BeerConsumer();
        bc2.setName("Scott");
        em.persist(bc2);
        BlueLight blueLight = new BlueLight();
        blueLight.setDiscount(10);
        blueLight.setUniqueKey(new BigInteger("2"));
        em.persist(blueLight);
        blueLight.setBeerConsumer(bc2);
        bc2.addBlueBeerToConsume(blueLight);
        em.flush();
        em.clear();
        clearCache();
        ReadAllQuery query = new ReadAllQuery();
        Expression selectionCriteria = new ExpressionBuilder().anyOf("blueBeersToConsume").treat(BlueLight.class).get("discount").equal(10);
        query.setSelectionCriteria(selectionCriteria);
        query.setReferenceClass(BeerConsumer.class);
        query.dontUseDistinct();
        Query jpaQuery = ((org.eclipse.persistence.internal.jpa.EntityManagerImpl) em.getDelegate()).createQuery(query);
        List expectedResult = jpaQuery.getResultList();
        clearCache();
        em.clear();
        // "SELECT e from Employee e join cast(e.project, LargeProject) p where p.budget = 1000
        CriteriaBuilder qb1 = em.getCriteriaBuilder();
        CriteriaQuery<BeerConsumer> cq1 = qb1.createQuery(BeerConsumer.class);
        Root<BeerConsumer> root = wrapper.from(cq1, BeerConsumer.class);
        Join<BeerConsumer, Blue> join = wrapper.join(root, BeerConsumer_blueBeersToConsume);
        jakarta.persistence.criteria.Expression exp = wrapper.get((Path) join.as(BlueLight.class), BlueLight_discount);
        cq1.where(qb1.equal(exp, 10));
        List<BeerConsumer> result = em.createQuery(cq1).getResultList();
        assertTrue("LargeProject cast failed.", comparer.compareObjects(result, expectedResult));
    } finally {
        if (isTransactionActive(em)) {
            this.rollbackTransaction(em);
        }
        closeEntityManager(em);
    }
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) Query(jakarta.persistence.Query) ReadObjectQuery(org.eclipse.persistence.queries.ReadObjectQuery) ReportQuery(org.eclipse.persistence.queries.ReportQuery) TypedQuery(jakarta.persistence.TypedQuery) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) Blue(org.eclipse.persistence.testing.models.jpa.inherited.Blue) ReadAllQuery(org.eclipse.persistence.queries.ReadAllQuery) BlueLight(org.eclipse.persistence.testing.models.jpa.inherited.BlueLight) ExpressionBuilder(org.eclipse.persistence.expressions.ExpressionBuilder) EntityManager(jakarta.persistence.EntityManager) JpaEntityManager(org.eclipse.persistence.jpa.JpaEntityManager) Expression(org.eclipse.persistence.expressions.Expression) BigInteger(java.math.BigInteger) List(java.util.List) ArrayList(java.util.ArrayList) BeerConsumer(org.eclipse.persistence.testing.models.jpa.inherited.BeerConsumer)

Aggregations

CriteriaQuery (jakarta.persistence.criteria.CriteriaQuery)96 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)82 EntityManager (jakarta.persistence.EntityManager)64 Query (jakarta.persistence.Query)63 List (java.util.List)54 TypedQuery (jakarta.persistence.TypedQuery)35 Employee (org.eclipse.persistence.testing.models.jpa.advanced.Employee)32 Test (org.junit.jupiter.api.Test)24 JpaQuery (org.eclipse.persistence.jpa.JpaQuery)20 JpaEntityManager (org.eclipse.persistence.jpa.JpaEntityManager)16 JpaCriteriaBuilder (org.eclipse.persistence.jpa.JpaCriteriaBuilder)14 Test (org.junit.Test)14 ArrayList (java.util.ArrayList)13 ReportQuery (org.eclipse.persistence.queries.ReportQuery)12 Query (org.hibernate.query.Query)12 QuerySQLTracker (org.eclipse.persistence.testing.framework.QuerySQLTracker)11 BasicEntity (org.hibernate.testing.orm.domain.gambit.BasicEntity)11 Root (jakarta.persistence.criteria.Root)8 HibernateCriteriaBuilder (org.hibernate.query.criteria.HibernateCriteriaBuilder)8 DatabasePlatform (org.eclipse.persistence.platform.database.DatabasePlatform)7