Search in sources :

Example 21 with TypedQuery

use of javax.persistence.TypedQuery in project crnk-framework by crnk-project.

the class JpaCriteriaQueryExecutorImpl method getTotalRowCount.

@Override
@SuppressWarnings({ "rawtypes" })
public long getTotalRowCount() {
    Selection<T> selection = query.getSelection();
    List<Order> orderList = query.getOrderList();
    try {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        Expression<Long> countExpr;
        Set<Root<?>> roots = query.getRoots();
        if (roots.size() != 1) {
            throw new IllegalStateException("cannot compute totalRowCount in case of multiple query roots");
        }
        if (!query.getGroupList().isEmpty()) {
            throw new IllegalStateException("cannot compute totalRowCount for grouped queries");
        }
        // transform query to a count query
        Root root = roots.iterator().next();
        countExpr = builder.count(root);
        query.multiselect(countExpr);
        query.orderBy(new ArrayList<Order>());
        TypedQuery countQuery = em.createQuery(query);
        return (Long) countQuery.getSingleResult();
    } finally {
        // transform count query back to regular query
        query.multiselect(selection);
        query.orderBy(orderList);
    }
}
Also used : TypedQuery(javax.persistence.TypedQuery)

Example 22 with TypedQuery

use of javax.persistence.TypedQuery in project OpenOLAT by OpenOLAT.

the class SharedWithMeQueries method searchSharedPagesEntries.

public List<AssessedPage> searchSharedPagesEntries(Identity member, SearchSharePagesParameters params) {
    StringBuilder sb = new StringBuilder(2048);
    sb.append("select binder.key,").append("  section.key, section.endDate,").append("  page.key, page.title, page.status, page.lastModified,").append("  body.lastModified,").append("  (select max(part.lastModified) from pfpagepart as part").append("   where part.body.key=body.key").append("  ) as partLastModified,").append("  uinfos.userStatus, uinfos.mark,").append("  owner").append(" from pfbinder as binder").append(" inner join binder.baseGroup as baseGroup").append(" inner join baseGroup.members as ownership on (ownership.role='").append(PortfolioRoles.owner.name()).append("')").append(" inner join ownership.identity as owner").append(" inner join fetch owner.user as owneruser").append(" inner join binder.sections as section").append(" inner join section.pages as page").append(" inner join page.body as body").append(params.isBookmarkOnly() ? " inner" : " left").append(" join pfpageuserinfos as uinfos on (uinfos.page.key=page.key and uinfos.identity.key=:identityKey)").append(" where ");
    if (params.isBookmarkOnly()) {
        sb.append(" uinfos.mark=true and");
    }
    String searchString = params.getSearchString();
    if (StringHelper.containsNonWhitespace(searchString)) {
        searchString = makeFuzzyQueryString(searchString);
        sb.append(" (");
        appendFuzzyLike(sb, "page.title", "searchString", dbInstance.getDbVendor());
        sb.append(") and");
    }
    if (params.getExcludedPageStatus() != null && !params.getExcludedPageStatus().isEmpty()) {
        sb.append(" (page.status is null or page.status not in (:excludedPageStatus)) and");
    }
    if (params.getExcludedPageUserStatus() != null && !params.getExcludedPageUserStatus().isEmpty()) {
        sb.append(" (uinfos.userStatus is null or uinfos.userStatus not in (:excludedPageUserStatus)) and");
    }
    sb.append(" (exists (select membership.key from bgroupmember as membership").append("   where membership.group.key=binder.baseGroup.key and membership.identity.key=:identityKey and membership.role in ('").append(PortfolioRoles.coach.name()).append("','").append(PortfolioRoles.reviewer.name()).append("')").append(" ) or exists (select sectionMembership.key from bgroupmember as sectionMembership").append("   where sectionMembership.group.key=section.baseGroup.key and sectionMembership.identity.key=:identityKey and sectionMembership.role in ('").append(PortfolioRoles.coach.name()).append("','").append(PortfolioRoles.reviewer.name()).append("')").append(" ) or exists (select page.key from pfpage as coachedPage").append("   inner join coachedPage.baseGroup as pageGroup").append("   inner join pageGroup.members as pageMembership on (pageMembership.identity.key=:identityKey and pageMembership.role in ('").append(PortfolioRoles.coach.name()).append("','").append(PortfolioRoles.reviewer.name()).append("'))").append("   where coachedPage.key=page.key").append(" ))");
    TypedQuery<Object[]> query = dbInstance.getCurrentEntityManager().createQuery(sb.toString(), Object[].class).setParameter("identityKey", member.getKey());
    if (StringHelper.containsNonWhitespace(searchString)) {
        query.setParameter("searchString", searchString.toLowerCase());
    }
    if (params.getExcludedPageStatus() != null && !params.getExcludedPageStatus().isEmpty()) {
        List<String> excludedPageStatus = params.getExcludedPageStatus().stream().map(s -> s.name()).collect(Collectors.toList());
        query.setParameter("excludedPageStatus", excludedPageStatus);
    }
    if (params.getExcludedPageUserStatus() != null && !params.getExcludedPageUserStatus().isEmpty()) {
        List<String> excludedPageUserStatus = params.getExcludedPageUserStatus().stream().map(s -> s.name()).collect(Collectors.toList());
        query.setParameter("excludedPageUserStatus", excludedPageUserStatus);
    }
    List<Object[]> objects = query.getResultList();
    List<AssessedPage> items = new ArrayList<>(objects.size());
    for (Object[] object : objects) {
        int pos = 0;
        Long binderKey = (Long) object[pos++];
        // Section key
        pos++;
        Date sectionDate = (Date) object[pos++];
        Long pageKey = (Long) object[pos++];
        String pageTitle = (String) object[pos++];
        PageStatus pageStatus = PageStatus.valueOfOrNull((String) object[pos++]);
        Date pageLastModified = (Date) object[pos++];
        Date bodyLastModified = (Date) object[pos++];
        Date partLastModified = (Date) object[pos++];
        PageUserStatus userStatus = PageUserStatus.valueOfWithDefault((String) object[pos++]);
        Boolean mark = (Boolean) object[pos++];
        Identity owner = (Identity) object[pos++];
        Date lastModified = pageLastModified;
        if (lastModified == null || (lastModified != null && partLastModified != null && partLastModified.after(lastModified))) {
            lastModified = partLastModified;
        }
        if (lastModified == null || (lastModified != null && bodyLastModified != null && bodyLastModified.after(lastModified))) {
            lastModified = bodyLastModified;
        }
        items.add(new AssessedPage(binderKey, sectionDate, pageKey, pageTitle, pageStatus, lastModified, mark, userStatus, owner));
    }
    return items;
}
Also used : PersistenceHelper.makeFuzzyQueryString(org.olat.core.commons.persistence.PersistenceHelper.makeFuzzyQueryString) SearchSharePagesParameters(org.olat.modules.portfolio.model.SearchSharePagesParameters) AssessedBinderSection(org.olat.modules.portfolio.model.AssessedBinderSection) Date(java.util.Date) Autowired(org.springframework.beans.factory.annotation.Autowired) TypedQuery(javax.persistence.TypedQuery) ArrayList(java.util.ArrayList) AssessedPage(org.olat.modules.portfolio.model.AssessedPage) HashSet(java.util.HashSet) BigDecimal(java.math.BigDecimal) Service(org.springframework.stereotype.Service) Map(java.util.Map) SectionStatus(org.olat.modules.portfolio.SectionStatus) StringHelper(org.olat.core.util.StringHelper) PersistenceHelper.appendFuzzyLike(org.olat.core.commons.persistence.PersistenceHelper.appendFuzzyLike) PageUserStatus(org.olat.modules.portfolio.PageUserStatus) Set(java.util.Set) BinderStatus(org.olat.modules.portfolio.BinderStatus) Collectors(java.util.stream.Collectors) List(java.util.List) DB(org.olat.core.commons.persistence.DB) Identity(org.olat.core.id.Identity) AssessedBinder(org.olat.modules.portfolio.model.AssessedBinder) PortfolioRoles(org.olat.modules.portfolio.PortfolioRoles) PageStatus(org.olat.modules.portfolio.PageStatus) PageStatus(org.olat.modules.portfolio.PageStatus) ArrayList(java.util.ArrayList) PersistenceHelper.makeFuzzyQueryString(org.olat.core.commons.persistence.PersistenceHelper.makeFuzzyQueryString) Date(java.util.Date) PageUserStatus(org.olat.modules.portfolio.PageUserStatus) AssessedPage(org.olat.modules.portfolio.model.AssessedPage) Identity(org.olat.core.id.Identity)

Example 23 with TypedQuery

use of javax.persistence.TypedQuery in project tests by datanucleus.

the class JPQLQueryTest method testTYPE.

public void testTYPE() {
    try {
        EntityManager em = getEM();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Person p = new Person(101, "Fred", "Flintstone", "fred.flintstone@jpox.com");
            em.persist(p);
            Employee e = new Employee(102, "Barney", "Rubble", "barney.rubble@jpox.com", 10000.0f, "12345");
            em.persist(e);
            em.flush();
            List<Person> result = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) <> Employee_Ann").getResultList();
            assertEquals(1, result.size());
            Person p1 = result.get(0);
            assertTrue(p1 instanceof Person && !(p1 instanceof Employee));
            List result2 = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN (Employee_Ann, Person_Ann)").getResultList();
            assertEquals(2, result2.size());
            List<Person> result3 = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN (Employee_Ann)").getResultList();
            assertEquals(1, result3.size());
            Person p3 = result3.get(0);
            assertTrue(p3 instanceof Employee);
            List<Person> result4 = em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) NOT IN (Employee_Ann)").getResultList();
            assertEquals(1, result4.size());
            Person p4 = result4.get(0);
            assertTrue(p4 instanceof Person && !(p4 instanceof Employee));
            Collection<String> collParam = new ArrayList<>();
            collParam.add("Employee_Ann");
            collParam.add("Person_Ann");
            TypedQuery<Person> q5 = (TypedQuery<Person>) em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN :collParam");
            q5.setParameter("collParam", collParam);
            List<Person> result5 = q5.getResultList();
            assertEquals(2, result5.size());
            Collection<Class> collParam2 = new ArrayList<>();
            collParam2.add(Employee.class);
            collParam2.add(Person.class);
            TypedQuery<Person> q6 = (TypedQuery<Person>) em.createQuery("SELECT p FROM " + Person.class.getName() + " p WHERE TYPE(p) IN :collParam");
            q6.setParameter("collParam", collParam2);
            List<Person> result6 = q6.getResultList();
            assertEquals(2, result6.size());
            // Test for TYPE using a discriminator sample
            User u = new User(1, "Basic User");
            em.persist(u);
            SuperUser su = new SuperUser(2, "Root", "Admin");
            em.persist(su);
            em.flush();
            List<Object[]> result7 = em.createQuery("SELECT u.name, TYPE(u) FROM " + User.class.getName() + " u ORDER BY u.id").getResultList();
            assertEquals(2, result7.size());
            Object[] result7_0 = result7.get(0);
            Object[] result7_1 = result7.get(1);
            assertEquals(2, result7_0.length);
            assertEquals("Basic User", result7_0[0]);
            assertEquals("User", result7_0[1]);
            assertEquals("Root", result7_1[0]);
            assertEquals("SuperUser", result7_1[1]);
            tx.rollback();
        } catch (Exception e) {
            LOG.error("Exception in query", e);
            fail("Exception in TYPE handling : " + e.getMessage());
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } finally {
        clean(Employee.class);
        clean(Person.class);
    }
}
Also used : EntityTransaction(javax.persistence.EntityTransaction) User(org.datanucleus.samples.annotations.inherited.User) SuperUser(org.datanucleus.samples.annotations.inherited.SuperUser) TypedQuery(javax.persistence.TypedQuery) ArrayList(java.util.ArrayList) NoResultException(javax.persistence.NoResultException) NonUniqueResultException(javax.persistence.NonUniqueResultException) PersistenceException(javax.persistence.PersistenceException) EntityManager(javax.persistence.EntityManager) Employee(org.datanucleus.samples.annotations.models.company.Employee) List(java.util.List) ArrayList(java.util.ArrayList) Person(org.datanucleus.samples.annotations.models.company.Person) SuperUser(org.datanucleus.samples.annotations.inherited.SuperUser)

Example 24 with TypedQuery

use of javax.persistence.TypedQuery in project muikku by otavanopisto.

the class WorkspaceJournalEntryDAO method listByWorkspaceEntityAndUserEntities.

public List<WorkspaceJournalEntry> listByWorkspaceEntityAndUserEntities(WorkspaceEntity workspaceEntity, Collection<UserEntity> userEntities, int firstResult, int maxResults) {
    EntityManager entityManager = getEntityManager();
    Set<Long> userEntityIds = userEntities.stream().map(userEntity -> userEntity.getId()).collect(Collectors.toSet());
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<WorkspaceJournalEntry> criteria = criteriaBuilder.createQuery(WorkspaceJournalEntry.class);
    Root<WorkspaceJournalEntry> root = criteria.from(WorkspaceJournalEntry.class);
    criteria.select(root);
    criteria.where(criteriaBuilder.and(criteriaBuilder.equal(root.get(WorkspaceJournalEntry_.workspaceEntityId), workspaceEntity.getId()), root.get(WorkspaceJournalEntry_.userEntityId).in(userEntityIds), criteriaBuilder.equal(root.get(WorkspaceJournalEntry_.archived), Boolean.FALSE)));
    criteria.orderBy(criteriaBuilder.desc(root.get(WorkspaceJournalEntry_.created)));
    TypedQuery<WorkspaceJournalEntry> query = entityManager.createQuery(criteria);
    query.setFirstResult(firstResult);
    query.setMaxResults(maxResults);
    return query.getResultList();
}
Also used : CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Date(java.util.Date) WorkspaceJournalEntry(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceJournalEntry) Collection(java.util.Collection) Set(java.util.Set) WorkspaceEntity(fi.otavanopisto.muikku.model.workspace.WorkspaceEntity) EntityManager(javax.persistence.EntityManager) Collectors(java.util.stream.Collectors) TypedQuery(javax.persistence.TypedQuery) List(java.util.List) WorkspaceJournalEntry_(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceJournalEntry_) CorePluginsDAO(fi.otavanopisto.muikku.plugins.CorePluginsDAO) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Root(javax.persistence.criteria.Root) UserEntity(fi.otavanopisto.muikku.model.users.UserEntity) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) WorkspaceJournalEntry(fi.otavanopisto.muikku.plugins.workspace.model.WorkspaceJournalEntry) EntityManager(javax.persistence.EntityManager)

Example 25 with TypedQuery

use of javax.persistence.TypedQuery in project tests by datanucleus.

the class CriteriaStringsTest method testCriteriaAttributeConverterParameter.

/**
 * Test query of entity with AttributeConverter field using Criteria and a parameter of the converter type
 */
public void testCriteriaAttributeConverterParameter() {
    EntityManager em = getEM();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        TypeHolder h = new TypeHolder(1, "First");
        h.setDetails(new ComplicatedType("FirstName", "LastName"));
        em.persist(h);
        em.flush();
        long id = h.getId();
        CriteriaBuilder cb = emf.getCriteriaBuilder();
        CriteriaQuery<TypeHolder> cq = cb.createQuery(TypeHolder.class);
        Root<TypeHolder> root = cq.from(TypeHolder.class);
        cq.where(cb.equal(root.get("details"), cb.parameter(ComplicatedType.class, "theDetails")));
        TypedQuery q = em.createQuery(cq);
        q.setParameter("theDetails", new ComplicatedType("FirstName", "LastName"));
        List<TypeHolder> results = q.getResultList();
        assertNotNull(results);
        assertEquals(1, results.size());
        TypeHolder hr = results.get(0);
        assertEquals(id, hr.getId());
        tx.rollback();
    } catch (Exception e) {
        LOG.error("Exception thrown during test", e);
        fail("Exception caught during test : " + e.getMessage());
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
Also used : TypeHolder(org.datanucleus.samples.attributeconverter.TypeHolder) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) EntityTransaction(javax.persistence.EntityTransaction) ComplicatedType(org.datanucleus.samples.attributeconverter.ComplicatedType) EntityManager(javax.persistence.EntityManager) TypedQuery(javax.persistence.TypedQuery)

Aggregations

TypedQuery (javax.persistence.TypedQuery)52 EntityManager (javax.persistence.EntityManager)28 List (java.util.List)24 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)24 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)21 ArrayList (java.util.ArrayList)16 Query (javax.persistence.Query)14 Predicate (javax.persistence.criteria.Predicate)14 Root (javax.persistence.criteria.Root)13 Map (java.util.Map)10 LinkedList (java.util.LinkedList)9 NoResultException (javax.persistence.NoResultException)9 Collectors (java.util.stream.Collectors)8 UserTransaction (javax.transaction.UserTransaction)8 Item (org.jpwh.model.querying.Item)8 Test (org.testng.annotations.Test)8 EntityTransaction (javax.persistence.EntityTransaction)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Set (java.util.Set)5