Search in sources :

Example 1 with TypedQuery

use of jakarta.persistence.TypedQuery in project hibernate-orm by hibernate.

the class SingularAttributeJoinTest method testEntityModeMapJoinCriteriaQuery.

@Test
public void testEntityModeMapJoinCriteriaQuery(EntityManagerFactoryScope scope) {
    scope.inEntityManager(entityManager -> {
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();
        jakarta.persistence.metamodel.EntityType distributionEntity = getEntityType(scope, "Distribution");
        From distributionFrom = criteriaQuery.from(distributionEntity);
        From policyJoin = distributionFrom.join("policy");
        Path policyId = policyJoin.get("policyId");
        criteriaQuery.select(policyId);
        TypedQuery typedQuery = entityManager.createQuery(criteriaQuery);
    });
}
Also used : CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) Path(jakarta.persistence.criteria.Path) TypedQuery(jakarta.persistence.TypedQuery) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) From(jakarta.persistence.criteria.From) Test(org.junit.jupiter.api.Test)

Example 2 with TypedQuery

use of jakarta.persistence.TypedQuery in project hibernate-orm by hibernate.

the class CriteriaToScrollableResultsFetchTest method getOrderLinesScrolled.

private List<OrderLine> getOrderLinesScrolled(Long facilityId) {
    EntityManager em = getOrCreateEntityManager();
    try {
        em.getTransaction().begin();
        Set<PurchaseOrg> purchaseOrgs = getPurchaseOrgsByFacilityId(facilityId, em);
        assertEquals("Expected one purchase organization.", 1, purchaseOrgs.size());
        System.out.println(purchaseOrgs);
        TypedQuery<OrderLine> query = getOrderLinesQuery(purchaseOrgs, em);
        Query hibernateQuery = query.unwrap(Query.class);
        hibernateQuery.setReadOnly(true);
        hibernateQuery.setCacheable(false);
        List<OrderLine> lines = new ArrayList<>();
        ScrollableResults scrollableResults = hibernateQuery.scroll();
        scrollableResults.last();
        int rows = scrollableResults.getRowNumber() + 1;
        scrollableResults.beforeFirst();
        while (scrollableResults.next()) {
            lines.add((OrderLine) scrollableResults.get());
        }
        assertNotNull(lines);
        assertEquals("Expected one order line", 1, lines.size());
        em.getTransaction().commit();
        return lines;
    } catch (Throwable t) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        throw t;
    } finally {
        em.close();
    }
}
Also used : EntityManager(jakarta.persistence.EntityManager) TypedQuery(jakarta.persistence.TypedQuery) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) Query(org.hibernate.query.Query) ArrayList(java.util.ArrayList) ScrollableResults(org.hibernate.ScrollableResults)

Example 3 with TypedQuery

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

the class MCRIFSCommands method moveContentToNewStore.

private static List<String> moveContentToNewStore(String sourceStore, String targetStore, String selectKey, String selectValue) {
    // check stores
    MCRContentStore fromStore = MCRContentStoreFactory.getStore(sourceStore);
    @SuppressWarnings("unused") MCRContentStore toStore = MCRContentStoreFactory.getStore(targetStore);
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<String> streamQuery = em.createQuery("SELECT id from MCRFSNODES where storeid=:storeid and " + selectKey + "=:selectValue order by owner", String.class).setParameter("storeid", fromStore.getID()).setParameter("selectValue", selectValue);
    try (Stream<String> resultStream = streamQuery.getResultStream()) {
        return resultStream.map(ifsId -> String.format(Locale.ROOT, "move ifs node %s to store %s", ifsId, targetStore)).collect(Collectors.toList());
    }
}
Also used : 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) MCRContentStore(org.mycore.datamodel.ifs.MCRContentStore)

Example 4 with TypedQuery

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

the class MCRIView2Commands method fixDeadEntries.

@MCRCommand(syntax = "fix dead tile jobs", help = "Deletes entries for files which dont exist anymore!")
public static void fixDeadEntries() {
    EntityManager em = MCREntityManagerProvider.getCurrentEntityManager();
    TypedQuery<MCRTileJob> allTileJobQuery = em.createNamedQuery("MCRTileJob.all", MCRTileJob.class);
    List<MCRTileJob> tiles = allTileJobQuery.getResultList();
    tiles.stream().filter(tj -> {
        MCRPath path = MCRPath.getPath(tj.getDerivate(), tj.getPath());
        return !Files.exists(path);
    }).peek(tj -> LOGGER.info("Delete TileJob {}:{}", tj.getDerivate(), tj.getPath())).forEach(em::remove);
}
Also used : TypedQuery(jakarta.persistence.TypedQuery) MCRIView2Tools(org.mycore.iview2.services.MCRIView2Tools) Enumeration(java.util.Enumeration) MCRException(org.mycore.common.MCRException) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) MCRRecursiveDeleter(org.mycore.datamodel.niofs.utils.MCRRecursiveDeleter) DirectoryStream(java.nio.file.DirectoryStream) JDOMException(org.jdom2.JDOMException) MCRImage(org.mycore.imagetiler.MCRImage) MCRTileJob(org.mycore.iview2.services.MCRTileJob) Locale(java.util.Locale) MCRTiledPictureProps(org.mycore.imagetiler.MCRTiledPictureProps) ZipFile(java.util.zip.ZipFile) MCRCommandGroup(org.mycore.frontend.cli.annotation.MCRCommandGroup) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) MCRMetadataManager(org.mycore.datamodel.metadata.MCRMetadataManager) MCRTilingQueue(org.mycore.iview2.services.MCRTilingQueue) ImageReader(javax.imageio.ImageReader) Files(java.nio.file.Files) MCRAbstractCommands(org.mycore.frontend.cli.MCRAbstractCommands) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRImageTiler(org.mycore.iview2.services.MCRImageTiler) IOException(java.io.IOException) FileSystem(java.nio.file.FileSystem) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) MCRCommandUtils(org.mycore.frontend.cli.MCRCommandUtils) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) MCREntityManagerProvider(org.mycore.backend.jpa.MCREntityManagerProvider) FileVisitResult(java.nio.file.FileVisitResult) List(java.util.List) Logger(org.apache.logging.log4j.Logger) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand) MCRObjectID(org.mycore.datamodel.metadata.MCRObjectID) EntityManager(jakarta.persistence.EntityManager) CRC32(java.util.zip.CRC32) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) EntityManager(jakarta.persistence.EntityManager) FileSystem(java.nio.file.FileSystem) MCRTileJob(org.mycore.iview2.services.MCRTileJob) MCRPath(org.mycore.datamodel.niofs.MCRPath) MCRCommand(org.mycore.frontend.cli.annotation.MCRCommand)

Example 5 with TypedQuery

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

the class AdvancedCriteriaQueryTestSuite method testTupleQuery.

/**
 * Test that a cache hit will occur on a primary key query.
 */
public void testTupleQuery() {
    EntityManager em = createEntityManager();
    QuerySQLTracker counter = null;
    beginTransaction(em);
    try {
        // Load an employee into the cache.
        CriteriaBuilder qb = em.getCriteriaBuilder();
        Query query = em.createQuery(em.getCriteriaBuilder().createQuery(Employee.class));
        List result = query.getResultList();
        Employee employee = (Employee) result.get(0);
        // Count SQL.
        counter = new QuerySQLTracker(getServerSession());
        // Query by primary key.
        CriteriaQuery<Tuple> cq = qb.createQuery(Tuple.class);
        Root<Employee> from = cq.from(Employee.class);
        cq.multiselect(from.get("id"), from.get("firstName"));
        cq.where(qb.and(qb.equal(from.get("id"), qb.parameter(from.get("id").getModel().getBindableJavaType(), "id")), qb.equal(from.get("firstName"), qb.parameter(from.get("firstName").getModel().getBindableJavaType(), "firstName"))));
        TypedQuery<Tuple> typedQuery = em.createQuery(cq);
        typedQuery.setParameter("id", employee.getId());
        typedQuery.setParameter("firstName", employee.getFirstName());
        Tuple queryResult = typedQuery.getSingleResult();
        assertTrue("Query Results do not match selection", queryResult.get(0).equals(employee.getId()) && queryResult.get(1).equals(employee.getFirstName()));
    } finally {
        rollbackTransaction(em);
        if (counter != null) {
            counter.remove();
        }
    }
}
Also used : JpaCriteriaBuilder(org.eclipse.persistence.jpa.JpaCriteriaBuilder) CriteriaBuilder(jakarta.persistence.criteria.CriteriaBuilder) EntityManager(jakarta.persistence.EntityManager) Employee(org.eclipse.persistence.testing.models.jpa.advanced.Employee) Query(jakarta.persistence.Query) TypedQuery(jakarta.persistence.TypedQuery) JpaQuery(org.eclipse.persistence.jpa.JpaQuery) CriteriaQuery(jakarta.persistence.criteria.CriteriaQuery) List(java.util.List) QuerySQLTracker(org.eclipse.persistence.testing.framework.QuerySQLTracker) Tuple(jakarta.persistence.Tuple)

Aggregations

TypedQuery (jakarta.persistence.TypedQuery)24 EntityManager (jakarta.persistence.EntityManager)18 Query (jakarta.persistence.Query)14 CriteriaQuery (jakarta.persistence.criteria.CriteriaQuery)11 ArrayList (java.util.ArrayList)8 List (java.util.List)8 CriteriaBuilder (jakarta.persistence.criteria.CriteriaBuilder)7 Collectors (java.util.stream.Collectors)4 LogManager (org.apache.logging.log4j.LogManager)4 Logger (org.apache.logging.log4j.Logger)4 Test (org.junit.Test)4 MCREntityManagerProvider (org.mycore.backend.jpa.MCREntityManagerProvider)4 MCRException (org.mycore.common.MCRException)4 Root (jakarta.persistence.criteria.Root)3 Test (org.junit.jupiter.api.Test)3 Tuple (jakarta.persistence.Tuple)2 Predicate (jakarta.persistence.criteria.Predicate)2 IOException (java.io.IOException)2 Files (java.nio.file.Files)2 MessageFormat (java.text.MessageFormat)2