Java Code Examples for javax.persistence.criteria.Root
The following are top voted examples for showing how to use javax.persistence.criteria.Root. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.
Example 1
Project: arquillian-showcase File: GameRepository.java View source code | 8 votes |
public List<Game> fetchAllFor(Platform platform) { CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<Game> query = criteriaBuilder.createQuery(Game.class); Root<Game> fromGames = query.from(Game.class); Join<Game, Platform> platformsOfGame = fromGames.join(Game_.supportedPlatforms); Predicate givenPlatfromIsAssigned = criteriaBuilder.equal(platformsOfGame.get(Platform_.name), platform.getName()); CriteriaQuery<Game> allGamesForGivenPlatfrom = query.select(fromGames) .where(givenPlatfromIsAssigned); return em.createQuery(allGamesForGivenPlatfrom).getResultList(); }
Example 2
Project: eclipselink.runtime File: CriteriaQueryTestSuite.java View source code | 8 votes |
public void testEqualsClauseSingleExpressionEmptyExpressionsList(){ EntityManager em = createEntityManager(); beginTransaction(em); try{ CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<Employee> query = criteriaBuilder.createQuery(Employee.class); Root<Employee> employee = query.from(Employee.class); EntityType<Employee> employeeModel = employee.getModel(); Predicate predicate = criteriaBuilder.equal(employee.get(employeeModel.getSingularAttribute("firstName", String.class)), "Bob"); List<Expression<Boolean>> expressions = predicate.getExpressions(); assertTrue("An empty list should be returned", expressions.isEmpty()); } finally { rollbackTransaction(em); closeEntityManager(em); } }
Example 3
Project: hibernateuniversity-devoxx File: UserManager.java View source code | 7 votes |
@Transactional public List<User> getUsersNamedEmmanuel() { EntityManager em = lazyEM.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); final CriteriaQuery<User> query = cb.createQuery( User.class ); final Root<User> u = query.from( User.class ); u.fetch( User_.addresses ); query.select( u ).distinct( true ).where( cb.equal( u.get( User_.firstName ), "Emmanuel" ) ); final TypedQuery<User> typedQuery = em.createQuery( query ); typedQuery.setFirstResult( 0 ).setMaxResults( 20 ); final List<User> resultList = typedQuery.getResultList(); return resultList; }
Example 4
Project: hibernateuniversity-devoxx File: UserManager.java View source code | 6 votes |
@Transactional public List<User> getUsersFromParis() { EntityManager em = lazyEM.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); final CriteriaQuery<User> query = cb.createQuery( User.class ); final Root<User> u = query.from( User.class ); final SetJoin<User,Address> a = u.join( User_.addresses ); u.fetch( User_.addresses ); query.select( u ).distinct( true ).where( cb.equal( a.get( Address_.city ), "Paris" ) ); final TypedQuery<User> typedQuery = em.createQuery( query ); typedQuery.setFirstResult( 0 ).setMaxResults( 20 ); final List<User> resultList = typedQuery.getResultList(); return resultList; }
Example 5
Project: VaadinUtils File: JpaBaseDao.java View source code | 6 votes |
public <V, J> List<E> findAllByAttributeJoin(SingularAttribute<E, J> joinAttr, SingularAttribute<J, V> vKey, V value, JoinType joinType) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<E> criteria = builder.createQuery(entityClass); Root<E> root = criteria.from(entityClass); Join<E, J> join = root.join(joinAttr, joinType); criteria.where(builder.equal(join.get(vKey), value)); return getEntityManager().createQuery(criteria).getResultList(); }
Example 6
Project: VaadinUtils File: JpaBaseDao.java View source code | 6 votes |
public <V, J> int deleteAllByAttributeJoin(SingularAttribute<J, V> vKey, V value, SingularAttribute<E, J> joinAttr) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaDelete<E> criteria = builder.createCriteriaDelete(entityClass); Root<E> root = criteria.from(entityClass); Join<E, J> join = root.join(joinAttr, JoinType.LEFT); criteria.where(builder.equal(join.get(vKey), value)); getEntityManager().getClass(); int result = getEntityManager().createQuery(criteria).executeUpdate(); return result; }
Example 7
Project: jpacontainer File: LocalEntityProvider.java View source code | 6 votes |
/** * Translates SortBy instances, which possibly contain nested properties * (e.g. name.firstName, name.lastName) into Order instances which can be * used in a CriteriaQuery. * * @param sortBy * the SortBy instance to translate * @param swapSortOrder * swaps the specified sort order if true. * @param cb * the {@link CriteriaBuilder} to use * @param root * the {@link CriteriaQuery} {@link Root} to be used. * @return */ protected Order translateSortBy(SortBy sortBy, boolean swapSortOrder, CriteriaBuilder cb, Root<T> root) { String sortedPropId = sortBy.getPropertyId().toString(); // First split the id and build a Path. String[] idStrings = sortedPropId.split("\\."); Path<T> path = null; if (idStrings.length > 1 && !isEmbedded(idStrings[0])) { // This is a nested property, we need to LEFT JOIN path = root.join(idStrings[0], JoinType.LEFT); for (int i = 1; i < idStrings.length; i++) { if (i < idStrings.length - 1) { path = ((Join<?, ?>) path) .join(idStrings[i], JoinType.LEFT); } else { path = path.get(idStrings[i]); } } } else { // non-nested or embedded, we can select as usual path = AdvancedFilterableSupport.getPropertyPathTyped(root, sortedPropId); } // Make and return the Order instances. if (sortBy.isAscending() != swapSortOrder) { return cb.asc(path); } else { return cb.desc(path); } }
Example 8
Project: clinic-softacad File: ImplicitJoinTest.java View source code | 6 votes |
@Test public void testImplicitJoinFromExplicitCollectionJoin() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); CriteriaQuery<Order> criteria = criteriaBuilder.createQuery( Order.class ); Root<Order> orderRoot = criteria.from( Order.class ); Join<Order, LineItem> lineItemsJoin = orderRoot.join( Order_.lineItems ); criteria.where( criteriaBuilder.lt( lineItemsJoin.get( LineItem_.quantity ), 2 ) ); criteria.select( orderRoot ).distinct( true ); TypedQuery<Order> query = em.createQuery( criteria ); query.getResultList(); em.getTransaction().commit(); em.close(); }
Example 9
Project: clinic-softacad File: UncorrelatedSubqueryTest.java View source code | 6 votes |
@Test public void testEqualAll() { CriteriaBuilder builder = entityManagerFactory().getCriteriaBuilder(); EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaQuery<Customer> criteria = builder.createQuery( Customer.class ); Root<Customer> customerRoot = criteria.from( Customer.class ); Join<Customer, Order> orderJoin = customerRoot.join( Customer_.orders ); criteria.select( customerRoot ); Subquery<Double> subCriteria = criteria.subquery( Double.class ); Root<Order> subqueryOrderRoot = subCriteria.from( Order.class ); subCriteria.select( builder.min( subqueryOrderRoot.get( Order_.totalPrice ) ) ); criteria.where( builder.equal( orderJoin.get( "totalPrice" ), builder.all( subCriteria ) ) ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); }
Example 10
Project: trade-manager File: TradingdayHome.java View source code | 6 votes |
/** * Method findTradestrategyByDate. * * @param open * Date * @return List<Tradestrategy> */ private List<Tradestrategy> findTradestrategyByIdTradingday( Integer idTradingday) { try { EntityManager entityManager = EntityManagerHelper .getEntityManager(); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Tradestrategy> query = builder .createQuery(Tradestrategy.class); Root<Tradestrategy> from = query.from(Tradestrategy.class); query.select(from); List<Predicate> predicates = new ArrayList<Predicate>(); if (null != idTradingday) { Join<Tradestrategy, Tradingday> tradingday = from .join("tradingday"); Predicate predicate = builder.equal( tradingday.get("idTradingDay"), idTradingday); predicates.add(predicate); } query.where(predicates.toArray(new Predicate[] {})); TypedQuery<Tradestrategy> typedQuery = entityManager .createQuery(query); List<Tradestrategy> items = typedQuery.getResultList(); return items; } catch (RuntimeException re) { throw re; } }
Example 11
Project: trade-manager File: CodeTypeHome.java View source code | 6 votes |
/** * Method findByAttributeName. * * @param codeTypeName * String * @param codeAttributeName * String * @return CodeValue */ public CodeValue findByAttributeName(String codeTypeName, String codeAttributeName) { try { EntityManager entityManager = EntityManagerHelper .getEntityManager(); entityManager.getTransaction().begin(); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<CodeValue> query = builder .createQuery(CodeValue.class); Root<CodeValue> from = query.from(CodeValue.class); query.select(from); List<Predicate> predicates = new ArrayList<Predicate>(); if (null != codeAttributeName) { Join<CodeValue, CodeAttribute> codeAttribute = from .join("codeAttribute"); Predicate predicate = builder.equal(codeAttribute.get("name"), codeAttributeName); predicates.add(predicate); Join<CodeAttribute, CodeType> codeType = codeAttribute .join("codeType"); Predicate predicate1 = builder.equal(codeType.get("name"), codeTypeName); predicates.add(predicate1); } query.where(predicates.toArray(new Predicate[] {})); TypedQuery<CodeValue> typedQuery = entityManager.createQuery(query); List<CodeValue> items = typedQuery.getResultList(); entityManager.getTransaction().commit(); if (items.size() > 0) { return items.get(0); } return null; } catch (RuntimeException re) { EntityManagerHelper.rollback(); throw re; } finally { EntityManagerHelper.close(); } }
Example 12
Project: eclipselink.runtime File: CriteriaQueryMetamodelTestSuite.java View source code | 6 votes |
public void testMetamodelOnClause() { EntityManager em = createEntityManager(); Query query = em.createQuery("Select e from Employee e join e.address a on a.city = 'Ottawa'"); List baseResult = query.getResultList(); CriteriaBuilder qb = em.getCriteriaBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Metamodel metamodel = em.getMetamodel(); EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class); EntityType<Address> entityAddr_ = metamodel.entity(Address.class); Root<Employee> root = cq.from(entityEmp_); Join address = root.join(entityEmp_.getSingularAttribute("address")); address.on(qb.equal(address.get(entityAddr_.getSingularAttribute("city")), "Ottawa")); List testResult = em.createQuery(cq).getResultList(); clearCache(); closeEntityManager(em); if (baseResult.size() != testResult.size()) { fail("Criteria query using ON clause did not match JPQL results; " +baseResult.size()+" were expected, while criteria query returned "+testResult.size()); } }
Example 13
Project: eclipselink.runtime File: CriteriaQueryMetamodelTestSuite.java View source code | 6 votes |
public void testMetamodelOnClauseOverCollection() { EntityManager em = createEntityManager(); Query query = em.createQuery("Select e from Employee e join e.phoneNumbers p on p.areaCode = '613'"); List baseResult = query.getResultList(); CriteriaBuilder qb = em.getCriteriaBuilder(); CriteriaQuery<Employee> cq = qb.createQuery(Employee.class); Metamodel metamodel = em.getMetamodel(); EntityType<Employee> entityEmp_ = metamodel.entity(Employee.class); EntityType<PhoneNumber> entityPhone_ = metamodel.entity(PhoneNumber.class); Root<Employee> root = cq.from(entityEmp_); Join phoneNumber = root.join(entityEmp_.getCollection("phoneNumbers")); phoneNumber.on(qb.equal(phoneNumber.get(entityPhone_.getSingularAttribute("areaCode")), "613")); List testResult = em.createQuery(cq).getResultList(); clearCache(); closeEntityManager(em); if (baseResult.size() != testResult.size()) { fail("Criteria query using ON clause did not match JPQL results; " +baseResult.size()+" were expected, while criteria query returned "+testResult.size()); } }
Example 14
Project: tapestry-model File: SearchableJpaGridDataSource.java View source code | 6 votes |
/** * {@inheritDoc} */ public void prepare(final int startIndex, final int endIndex, final List<SortConstraint> sortConstraints) { final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery criteria = builder.createQuery(entityType); final Root root = criteria.from(entityType); applyAdditionalConstraints(criteria.select(root), root, builder); for (final SortConstraint constraint : sortConstraints) { final String propertyName = constraint.getPropertyModel().getPropertyName(); final Path<Object> propertyPath = root.get(propertyName); switch (constraint.getColumnSort()) { case ASCENDING: criteria.orderBy(builder.asc(propertyPath)); break; case DESCENDING: criteria.orderBy(builder.desc(propertyPath)); break; default: } } final TypedQuery<?> query = entityManager.createQuery(criteria); query.setFirstResult(startIndex); query.setMaxResults(endIndex - startIndex + 1); this.startIndex = startIndex; preparedResults = query.getResultList(); }
Example 15
Project: richfaces File: JPADataModel.java View source code | 6 votes |
private List<Order> createOrders(CriteriaBuilder criteriaBuilder, Root<T> root) { List<Order> orders = Lists.newArrayList(); List<SortField> sortFields = arrangeableState.getSortFields(); if (sortFields != null && !sortFields.isEmpty()) { FacesContext facesContext = FacesContext.getCurrentInstance(); for (SortField sortField : sortFields) { String propertyName = (String) sortField.getSortBy().getValue(facesContext.getELContext()); Path<Object> expression = root.get(propertyName); Order jpaOrder; SortOrder sortOrder = sortField.getSortOrder(); if (sortOrder == SortOrder.ascending) { jpaOrder = criteriaBuilder.asc(expression); } else if (sortOrder == SortOrder.descending) { jpaOrder = criteriaBuilder.desc(expression); } else { throw new IllegalArgumentException(sortOrder.toString()); } orders.add(jpaOrder); } } return orders; }
Example 16
Project: btpka3.github.com File: JpaTest.java View source code | 6 votes |
public static void list(EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); CriteriaBuilder cb = emf.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> r = cq.from(User.class); Path<Long> idPath = r.get("id"); cq.where( cb.ge(idPath, 5L), cb.and(cb.ge(idPath, 5L)) ).orderBy(cb.asc(r.get("id"))); List<User> userList = em.createQuery(cq) .setFirstResult(1) // = offset .setMaxResults(10) // = limit // .setHint("org.hibernate.fetchSize", 1) .getResultList(); for (User user : userList) { System.out.println(user); } em.close(); System.out.println("List finished."); }
Example 17
Project: hibernateuniversity-devoxx File: UserManager.java View source code | 6 votes |
@Transactional public void displayAvgCreditByGender() { EntityManager em = lazyEM.get(); CriteriaBuilder cb = em.getCriteriaBuilder(); final CriteriaQuery<Tuple> query = cb.createTupleQuery(); final Root<User> u = query.from( User.class ); final Path<Gender> gender = u.get( User_.gender ); gender.alias( "gender" ); final Selection<Double> credits = cb.avg( u.get( User_.credits ) ).alias( "credits" ); query.multiselect( credits, gender, cb.count( u ).alias( "nbr" )) .groupBy( gender ) .having( cb.in( gender) .value( Gender.FEMALE ) .value( Gender.MALE ) ) .orderBy( cb.desc( gender ) ); final TypedQuery<Tuple> typedQuery = em.createQuery( query ); typedQuery.setFirstResult( 0 ).setMaxResults( 20 ); final List<Tuple> list = typedQuery.getResultList(); for (Tuple tuple : list) { final Double average = tuple.get( credits ); System.err.println("Avg credit " + tuple.get( credits ) + " " + tuple.get( "gender" ) + " found " + tuple.get( "nbr" ) + " times"); } }
Example 18
Project: tapestry-5 File: JpaGridDataSource.java View source code | 6 votes |
/** * {@inheritDoc} */ @Override public void prepare(final int startIndex, final int endIndex, final List<SortConstraint> sortConstraints) { final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery<E> criteria = builder.createQuery(entityType); final Root<E> root = criteria.from(entityType); applyAdditionalConstraints(criteria.select(root), root, builder); for (final SortConstraint constraint : sortConstraints) { final String propertyName = constraint.getPropertyModel().getPropertyName(); final Path<Object> propertyPath = root.get(propertyName); switch (constraint.getColumnSort()) { case ASCENDING: criteria.orderBy(builder.asc(propertyPath)); break; case DESCENDING: criteria.orderBy(builder.desc(propertyPath)); break; default: } } final TypedQuery<E> query = entityManager.createQuery(criteria); query.setFirstResult(startIndex); query.setMaxResults(endIndex - startIndex + 1); this.startIndex = startIndex; preparedResults = query.getResultList(); }
Example 19
Project: Netuno File: NavioServiceImpl.java View source code | 6 votes |
@Override public List<Navio> filtrar(Navio navio) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Navio> consulta = cb.createQuery(Navio.class); Root<Navio> navioRoot = consulta.from(Navio.class); ArrayList<Predicate> predicados = new ArrayList<Predicate>(); if(navio!=null){ if(navio.getNome()!=null && !navio.getNome().equals("")){ Expression<String> nome = navioRoot.get("nome"); predicados.add(cb.like(cb.lower(nome), navio.getNome().toLowerCase()+"%")); } } consulta.select(navioRoot).where(predicados.toArray(new Predicate[]{})); consulta.orderBy(cb.asc((navioRoot.get("nome")))); return em.createQuery(consulta).getResultList(); }
Example 20
Project: searchisko File: TaskPersisterJpa.java View source code | 6 votes |
@Override public List<TaskStatusInfo> listTasks(String taskTypeFilter, List<TaskStatus> taskStatusFilter, int from, int size) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TaskStatusInfo> queryList = cb.createQuery(TaskStatusInfo.class); Root<TaskStatusInfo> root = queryList.from(TaskStatusInfo.class); queryList.select(root); List<Predicate> filter = new ArrayList<>(); if (taskStatusFilter != null && !taskStatusFilter.isEmpty()) { Expression<String> taskStatus = root.get("taskStatus"); filter.add(taskStatus.in(taskStatusFilter)); } if (taskTypeFilter != null && !taskTypeFilter.trim().isEmpty()) { filter.add(cb.equal(root.get("taskType"), taskTypeFilter)); } if (filter.size() > 0) { queryList.where(filter.toArray(new Predicate[filter.size()])); } queryList.orderBy(cb.desc(root.get("taskCreatedAt"))); TypedQuery<TaskStatusInfo> q = em.createQuery(queryList); if (from >= 0) q.setFirstResult(from); if (size > 0) q.setMaxResults(size); return q.getResultList(); }
Example 21
Project: catwatch File: ContributorRepositoryImpl.java View source code | 6 votes |
@Override public List<Contributor> findAllTimeTopContributors(Long organizationId, Date snapshotDate, String namePrefix, Integer offset, Integer limit) { checkNotNull(snapshotDate, "snapshot date must not be null but was"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Contributor> cq = cb.createQuery(Contributor.class); // define "from" and joins Root<Contributor> contributor = cq.from(Contributor.class); Path<ContributorKey> key = contributor.get("key"); // define constraints List<Predicate> andPredicates = new ArrayList<Predicate>(); { if (organizationId != null) { andPredicates.add(cb.equal(key.get("organizationId"), organizationId)); } andPredicates.add(cb.equal(key.<Date> get("snapshotDate"), snapshotDate)); if (namePrefix != null) { andPredicates.add(cb.like(contributor.get("name"), namePrefix.replace("%", "[%]") + "%")); } } return em .createQuery(cq // .select(contributor) // .where(andPredicates.toArray(new Predicate[andPredicates.size()])) // .orderBy(cb.desc(contributor.get("organizationalCommitsCount")))) .setFirstResult(offset == null ? 0 : offset) // .setMaxResults(limit == null ? 10000000 : limit) // .getResultList(); }
Example 22
Project: idnadrev File: ViewCategoryController.java View source code | 6 votes |
protected <T extends Information<T>> void deleteReferences(EntityManager em, Category reload, CriteriaBuilder builder, Class<T> clazz) { CriteriaUpdate<T> update = builder.createCriteriaUpdate(clazz); Root<T> root = update.from(clazz); Path<Category> contextPath = root.get(KEY_CATEGORY); update.set(contextPath, builder.nullLiteral(Category.class)); update.where(builder.equal(contextPath, reload)); em.createQuery(update).executeUpdate(); }
Example 23
Project: uPortal File: JpaPortletDefinitionDao.java View source code | 6 votes |
/** * Add all the fetches needed for completely loading the object graph */ protected void addFetches(final Root<PortletDefinitionImpl> definitionRoot) { definitionRoot.fetch(PortletDefinitionImpl_.portletPreferences, JoinType.LEFT) .fetch(PortletPreferencesImpl_.portletPreferences, JoinType.LEFT) .fetch(PortletPreferenceImpl_.values, JoinType.LEFT); definitionRoot.fetch(PortletDefinitionImpl_.parameters, JoinType.LEFT); definitionRoot.fetch(PortletDefinitionImpl_.localizations, JoinType.LEFT); }
Example 24
Project: clinic-softacad File: CriteriaCompilingTest.java View source code | 6 votes |
@Test public void testSimpleFetchCriteria() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); // String based... CriteriaQuery<Order> criteria = em.getCriteriaBuilder().createQuery( Order.class ); Root<Order> root = criteria.from( Order.class ); root.fetch( "lineItems" ); criteria.select( root ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); }
Example 25
Project: eclipselink.runtime File: CriteriaQueryCastTestSuite.java View source code | 6 votes |
public void testDowncastWithFetchJoin(){ EntityManager em = createEntityManager(); beginTransaction(em); try { Person rudy = new Person(); rudy.setName("Rudy"); em.persist(rudy); SportsCar sportsCar = new SportsCar(); sportsCar.setMaxSpeed(200); em.persist(sportsCar); rudy.setCar(sportsCar); Person theo = new Person(); theo.setName("Theo"); em.persist(theo); Jalopy car = new Jalopy(); car.setColor("Red"); car.setPercentRust(20); em.persist(car); theo.setCar(car); em.flush(); clearCache(); em.clear(); //Query query = em.createQuery("Select p from Person p join fetch p.car join treat(p.car as SportsCar) s where s.maxSpeed = 200"); CriteriaBuilder qb = em.getCriteriaBuilder(); CriteriaQuery<Person> cq = qb.createQuery(Person.class); Root<Person> root = cq.from(Person.class); root.fetch("car"); Join s = qb.treat(root.join("car"), SportsCar.class); cq.where(qb.equal(s.get("maxSpeed"), 200)); List resultList = em.createQuery(cq).getResultList(); Person person = (Person)resultList.get(0); assertTrue("Incorrect result size returned", resultList.size() == 1); assertNotNull("The car was not fetched.", person.car); } finally { if (this.isTransactionActive(em)){ rollbackTransaction(em); } closeEntityManager(em); } }
Example 26
Project: sculptor File: JpaFindByConditionAccessImplGeneric.java View source code | 6 votes |
@Override protected void prepareFetch(Root<T> root, QueryConfig config) { for (ConditionalCriteria criteria : conditionalCriterias) { if (Operator.FetchEager.equals(criteria.getOperator())) { // TODO: this is not tested root.fetch(criteria.getPropertyFullName()); } else if (Operator.FetchLazy.equals(criteria.getOperator())) { // TODO: fetchLazy is not supported actually } } }
Example 27
Project: jdal File: TestJpaDao.java View source code | 6 votes |
@Test @Transactional public void testCopy() { EntityManager em = bookDao.getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Book> criteria = cb.createQuery(Book.class); // Fetch join Root<Book> root = criteria.from(Book.class); Path<String> path = root.join("author").<String>get("name"); root.fetch("author"); criteria.select(root); // SubQuery Subquery<String> sq = criteria.subquery(String.class); Root<Author> author = sq.from(Author.class); sq.select(author.<String>get("name")); sq.where(cb.equal(author.<String>get("name"), "Rod")); criteria.where(cb.in(path).value(sq)); CriteriaQuery<Book> copy = cb.createQuery(Book.class); JpaUtils.copyCriteria(criteria, copy); List<Book> copyBooks = em.createQuery(copy).getResultList(); List<Book> books = em.createQuery(criteria).getResultList(); assertEquals(books, copyBooks); }
Example 28
Project: swag4911 File: AbstractDataAccessObject.java View source code | 6 votes |
private <T> List<T> findByExample(T example, Class<T> clazz) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException { EntityManager em = getEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(clazz); Root<T> r = cq.from(clazz); Predicate p = cb.conjunction(); Metamodel mm = em.getMetamodel(); EntityType<T> et = mm.entity(clazz); Set<Attribute<? super T, ?>> attrs = et.getAttributes(); for (Attribute<? super T, ?> a : attrs) { String name = a.getName(); String javaName = a.getJavaMember().getName(); String getter = "get" + javaName.substring(0, 1).toUpperCase() + javaName.substring(1); Method m = clazz.getMethod(getter, (Class<?>[]) null); Object value = m.invoke(example, (Object[]) null); if (value != null) { if (!a.isCollection()) p = cb.and(p, cb.equal(r.get(name), value)); if (a.isAssociation()) r.fetch(name); } } cq.select(r).where(p); TypedQuery<T> query = em.createQuery(cq); return query.getResultList(); }
Example 29
Project: hibernate-orm File: FetchAndJoinTest.java View source code | 6 votes |
@Test public void testImplicitJoinFromExplicitCollectionJoin() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); final CriteriaBuilder builder = em.getCriteriaBuilder(); final CriteriaQuery<Entity1> criteria = builder.createQuery(Entity1.class); final Root<Entity1> root = criteria.from(Entity1.class); final Join<Entity1, Entity2> entity2Join = root.join( Entity1_.entity2, JoinType.INNER); // illegal with fetch join final Fetch<Entity1, Entity2> entity2Fetch = root.fetch(Entity1_.entity2, JoinType.INNER); // <=== REMOVE entity2Fetch.fetch( Entity2_.entity3 ); // <=== REMOVE criteria.where(builder.equal(root.get(Entity1_.value), "test"), builder.equal(entity2Join.get(Entity2_.value), "test")); // illegal with fetch join em.createQuery(criteria).getResultList(); em.getTransaction().commit(); em.close(); }
Example 30
Project: hibernate-core-ogm File: CriteriaCompilingTest.java View source code | 6 votes |
@Test public void testSimpleFetchCriteria() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); // String based... CriteriaQuery<Order> criteria = em.getCriteriaBuilder().createQuery( Order.class ); Root<Order> root = criteria.from( Order.class ); root.fetch( "lineItems" ); criteria.select( root ); em.createQuery( criteria ).getResultList(); em.getTransaction().commit(); em.close(); }
Example 31
Project: tapestry-model File: SearchableJpaGridDataSource.java View source code | 6 votes |
/** * Invoked after the main criteria has been set up (firstResult, maxResults and any sort contraints). This gives subclasses a chance to * apply additional constraints before the list of results is obtained from the criteria. This implementation does nothing and may be * overridden. */ @SuppressWarnings({ "rawtypes", "unchecked" }) protected Predicate applyAdditionalConstraints(CriteriaBuilder builder, Root<?> root, Predicate existingPredicate) { if ((includedIds == null || includedIds.size() <= 0) && (propertySearchFilterMap == null || propertySearchFilterMap.size() <= 0)) return existingPredicate; List<Predicate> predicates = new ArrayList<Predicate>(propertySearchFilterMap.entrySet().size()); if (existingPredicate != null) predicates.add(existingPredicate); if (includedIds != null) { EntityType entityType = root.getModel(); SingularAttribute idAttr = entityType.getId(entityType.getIdType().getJavaType()); predicates.add(root.get(idAttr).in(includedIds)); } for (Entry<TynamoPropertyDescriptor, SearchFilterPredicate> entry : propertySearchFilterMap.entrySet()) predicates.add(createPredicate(builder, root, entry.getKey().getName(), entry.getValue())); return builder.and(predicates.toArray(new Predicate[predicates.size()])); }
Example 32
Project: clinic-softacad File: QueryBuilderTest.java View source code | 6 votes |
@Test public void testConstructor() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); CriteriaQuery<Customer> cquery = cb.createQuery(Customer.class); Root<Customer> customer = cquery.from(Customer.class); EntityType<Customer> Customer_ = customer.getModel(); cquery.select( cb.construct( Customer.class, customer.get(Customer_.getSingularAttribute("id", String.class)), customer.get(Customer_.getSingularAttribute("name", String.class)) ) ); TypedQuery<Customer> tq = em.createQuery(cquery); tq.getResultList(); em.getTransaction().commit(); em.close(); }
Example 33
Project: eclipselink.runtime File: SubQueryImpl.java View source code | 6 votes |
/** * Correlates a root of the enclosing query to a root of the subquery and * returns the subquery root. * * @param parentRoot * a root of the containing query * @return subquery root */ @Override public <Y> Root<Y> correlate(Root<Y> parentRoot){ RootImpl root = new RootImpl(parentRoot.getModel(), metamodel, parentRoot.getJavaType(), internalCorrelate((FromImpl)parentRoot), parentRoot.getModel(), (FromImpl) parentRoot); integrateRoot(root); return root; }
Example 34
Project: hibernate-orm File: QueryBuilderTest.java View source code | 6 votes |
@Test public void testConstructor() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); CriteriaQuery<Customer> cquery = cb.createQuery(Customer.class); Root<Customer> customer = cquery.from(Customer.class); EntityType<Customer> Customer_ = customer.getModel(); cquery.select( cb.construct( Customer.class, customer.get(Customer_.getSingularAttribute("id", String.class)), customer.get(Customer_.getSingularAttribute("name", String.class)) ) ); TypedQuery<Customer> tq = em.createQuery(cquery); tq.getResultList(); em.getTransaction().commit(); em.close(); }
Example 35
Project: hibernate-orm File: CriteriaCompilingTest.java View source code | 6 votes |
@Test public void testTrim() { final String expectedResult = "David R. Vincent"; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Customer customer = new Customer( ); customer.setId( "id" ); customer.setName( " David R. Vincent " ); em.persist( customer ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); EntityTransaction et = em.getTransaction(); et.begin(); CriteriaQuery<String> cquery = cb.createQuery( String.class ); Root<Customer> cust = cquery.from( Customer.class ); //Get Metamodel from Root EntityType<Customer> Customer_ = cust.getModel(); cquery.where( cb.equal( cust.get( Customer_.getSingularAttribute( "name", String.class ) ), cb.literal( " David R. Vincent " ) ) ); cquery.select( cb.trim( CriteriaBuilder.Trimspec.BOTH, cust.get( Customer_.getSingularAttribute( "name", String.class ) ) ) ); TypedQuery<String> tq = em.createQuery( cquery ); String result = tq.getSingleResult(); et.commit(); em.close(); Assert.assertEquals( "Mismatch in received results", expectedResult, result ); }
Example 36
Project: hibernate-core-ogm File: QueryBuilderTest.java View source code | 6 votes |
@Test public void testConstructor() { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); CriteriaBuilderImpl cb = (CriteriaBuilderImpl) em.getCriteriaBuilder(); MetamodelImpl mm = (MetamodelImpl) em.getMetamodel(); CriteriaQuery<Customer> cquery = cb.createQuery(Customer.class); Root<Customer> customer = cquery.from(Customer.class); EntityType<Customer> Customer_ = customer.getModel(); cquery.select( cb.construct( Customer.class, customer.get(Customer_.getSingularAttribute("id", String.class)), customer.get(Customer_.getSingularAttribute("name", String.class)) ) ); TypedQuery<Customer> tq = em.createQuery(cquery); tq.getResultList(); em.getTransaction().commit(); em.close(); }
Example 37
Project: cmop File: DynamicSpecifications.java View source code | 5 votes |
public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> clazz) { return new Specification<T>() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) { if (Collections3.isNotEmpty(filters)) { List<Predicate> predicates = Lists.newArrayList(); for (SearchFilter filter : filters) { // nested path translate, ?Task???"user.name"?filedName, // ???Task.user.name?? String[] names = StringUtils.split(filter.fieldName, "."); Path expression = root.get(names[0]); for (int i = 1; i < names.length; i++) { expression = expression.get(names[i]); } // logic operator switch (filter.operator) { case EQ: predicates.add(builder.equal(expression, filter.value)); break; case LIKE: predicates.add(builder.like(expression, "%" + filter.value + "%")); break; case GT: predicates.add(builder.greaterThan(expression, (Comparable) filter.value)); break; case LT: predicates.add(builder.lessThan(expression, (Comparable) filter.value)); break; case GTE: predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable) filter.value)); break; case LTE: predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) filter.value)); break; case NOT: predicates.add(builder.notEqual(expression, (Comparable) filter.value)); break; case IsNull: predicates.add(builder.isNull(expression)); break; case NotNull: predicates.add(builder.isNotNull(expression)); break; } } // ?????? and ???? if (predicates.size() > 0) { return builder.and(predicates.toArray(new Predicate[predicates.size()])); } } return builder.conjunction(); } }; }
Example 38
Project: clinic-softacad File: CriteriaCompilingTest.java View source code | 5 votes |
@Test @RequiresDialect( DB2Dialect.class ) @FailureExpected( jiraKey = "HHH-6655" ) public void testTrim() { final String expectedResult = "David R. Vincent"; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Customer customer = new Customer( ); customer.setId( "id" ); customer.setName( " David R. Vincent " ); em.persist( customer ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); EntityTransaction et = em.getTransaction(); et.begin(); CriteriaQuery<String> cquery = cb.createQuery( String.class ); Root<Customer> cust = cquery.from( Customer.class ); //Get Metamodel from Root EntityType<Customer> Customer_ = cust.getModel(); cquery.where( cb.equal( cust.get( Customer_.getSingularAttribute( "name", String.class ) ), cb.literal( " David R. Vincent " ) ) ); cquery.select( cb.trim( CriteriaBuilder.Trimspec.BOTH, cust.get( Customer_.getSingularAttribute( "name", String.class ) ) ) ); TypedQuery<String> tq = em.createQuery( cquery ); String result = tq.getSingleResult(); et.commit(); em.close(); Assert.assertEquals( "Mismatch in received results", expectedResult, result ); }
Example 39
Project: hibernate-core-ogm File: CriteriaCompilingTest.java View source code | 5 votes |
@Test @RequiresDialect( DB2Dialect.class ) @FailureExpected( jiraKey = "HHH-6655" ) public void testTrim() { final String expectedResult = "David R. Vincent"; EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); Customer customer = new Customer( ); customer.setId( "id" ); customer.setName( " David R. Vincent " ); em.persist( customer ); em.getTransaction().commit(); em.close(); em = getOrCreateEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); EntityTransaction et = em.getTransaction(); et.begin(); CriteriaQuery<String> cquery = cb.createQuery( String.class ); Root<Customer> cust = cquery.from( Customer.class ); //Get Metamodel from Root EntityType<Customer> Customer_ = cust.getModel(); cquery.where( cb.equal( cust.get( Customer_.getSingularAttribute( "name", String.class ) ), cb.literal( " David R. Vincent " ) ) ); cquery.select( cb.trim( CriteriaBuilder.Trimspec.BOTH, cust.get( Customer_.getSingularAttribute( "name", String.class ) ) ) ); TypedQuery<String> tq = em.createQuery( cquery ); String result = tq.getSingleResult(); et.commit(); em.close(); Assert.assertEquals( "Mismatch in received results", expectedResult, result ); }