public void testManyToManyFilterOnCriteria() { TestData testData = new TestData(); testData.prepare(); Session session = openSession(); session.enableFilter( "effectiveDate" ).setParameter( "asOfDate", new Date() ); Product prod = ( Product ) session.createCriteria( Product.class ) .setResultTransformer( new DistinctRootEntityResultTransformer() ) .add( Expression.eq( "id", testData.prod1Id ) ) .uniqueResult(); assertNotNull( prod ); assertEquals( "Incorrect Product.categories count for filter", 1, prod.getCategories().size() ); session.close(); testData.release(); }
@SuppressWarnings("unchecked") private Map<Long, List<TaskData>> loadJobsTasks(Session session, List<Long> jobIds) { Query tasksQuery = session.getNamedQuery("loadJobsTasks") .setParameterList("ids", jobIds) .setReadOnly(true) .setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE); Map<Long, List<TaskData>> tasksMap = new HashMap<>(jobIds.size(), 1f); for (Long id : jobIds) { tasksMap.put(id, new ArrayList<TaskData>()); } List<TaskData> tasks = tasksQuery.list(); for (TaskData task : tasks) { tasksMap.get(task.getJobData().getId()).add(task); } return tasksMap; }
public Query toQuery(Session session, boolean isReadOnly) { org.hibernate.Query query = session.createQuery(toHql()); for (Map.Entry<String,Object> arg : args().entrySet()) { if (arg.getKey().endsWith(SET_ARG_SUFFIX)) { // HACK: handle 'list' type parameters, used with the 'IN (?)' operator query.setParameterList(arg.getKey(), (Set<?>) arg.getValue()); } else { query.setParameter(arg.getKey(), arg.getValue()); } } if (_isDistinctRootEntities) { query.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE); } query.setReadOnly(isReadOnly); return query; }
/** * @return all objects of this Entity type */ @SuppressWarnings("unchecked") protected List<EntityClass> getAllObjects() { List<EntityClass> objects = new ArrayList<>(); Session session = null; try { session = sessionFactory.openSession(); Criteria criteria = session.createCriteria(getEntityType()); //make uniq, criteria returns many double entities, because of fetched relations //http://stackoverflow.com/questions/8758363/why-session-createcriteriaclasstype-list-return-more-object-than-in-list criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE); objects = criteria.list(); } catch (RuntimeException re) { re.printStackTrace(); } finally { if (session != null) { session.close(); } } return objects; }
public void testSQLQueryInterface() { Session s = openSession(); Transaction t = s.beginTransaction(); Organization ifa = new Organization("IFA"); Organization jboss = new Organization("JBoss"); Person gavin = new Person("Gavin"); Employment emp = new Employment(gavin, jboss, "AU"); s.persist(ifa); s.persist(jboss); s.persist(gavin); s.persist(emp); List l = s.createSQLQuery( getOrgEmpRegionSQL() ) .addEntity("org", Organization.class) .addJoin("emp", "org.employments") .addScalar("regionCode", Hibernate.STRING) .list(); assertEquals( 2, l.size() ); l = s.createSQLQuery( getOrgEmpPersonSQL() ) .addEntity("org", Organization.class) .addJoin("emp", "org.employments") .addJoin("pers", "emp.employee") .list(); assertEquals( l.size(), 1 ); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); l = s.createSQLQuery( "select {org.*}, {emp.*} " + "from ORGANIZATION org " + " left outer join EMPLOYMENT emp on org.ORGID = emp.EMPLOYER, ORGANIZATION org2" ) .addEntity("org", Organization.class) .addJoin("emp", "org.employments") .setResultTransformer(new DistinctRootEntityResultTransformer()) .list(); assertEquals( l.size(), 2 ); t.commit(); s.close(); s = openSession(); t = s.beginTransaction(); s.delete(emp); s.delete(gavin); s.delete(ifa); s.delete(jboss); t.commit(); s.close(); }
public void testResultTransformerScalarQueries() throws Exception { createTestBaseData(); String query = "select an.description as description, an.bodyWeight as bodyWeight from Animal an order by bodyWeight desc"; Session session = openSession(); List results = session.createQuery( query ) .setResultTransformer(Transformers.aliasToBean(Animal.class)).list(); assertEquals( "Incorrect result size", results.size(), 2 ); assertTrue( "Incorrect return type", results.get(0) instanceof Animal ); Animal firstAnimal = (Animal) results.get(0); Animal secondAnimal = (Animal) results.get(1); assertEquals("Mammal #1", firstAnimal.getDescription()); assertEquals("Mammal #2", secondAnimal.getDescription()); assertFalse(session.contains(firstAnimal)); session.close(); session = openSession(); Iterator iter = session.createQuery( query ) .setResultTransformer(Transformers.aliasToBean(Animal.class)).iterate(); assertTrue( "Incorrect result size", iter.hasNext() ); assertTrue( "Incorrect return type", iter.next() instanceof Animal ); session.close(); session = openSession(); ScrollableResults sr = session.createQuery( query ) .setResultTransformer(Transformers.aliasToBean(Animal.class)).scroll(); assertTrue( "Incorrect result size", sr.next() ); assertTrue( "Incorrect return type", sr.get(0) instanceof Animal ); assertFalse(session.contains(sr.get(0))); sr.close(); session.close(); session = openSession(); results = session.createQuery( "select a from Animal a, Animal b order by a.id" ) .setResultTransformer(new DistinctRootEntityResultTransformer()) .list(); assertEquals( "Incorrect result size", 2, results.size()); assertTrue( "Incorrect return type", results.get(0) instanceof Animal ); firstAnimal = (Animal) results.get(0); secondAnimal = (Animal) results.get(1); assertEquals("Mammal #1", firstAnimal.getDescription()); assertEquals("Mammal #2", secondAnimal.getDescription()); session.close(); destroyTestBaseData(); }
/** * Executes a query that is built using full text search, core column filters, and extension column filters. The filters * and sorting to be applied are provided via the criteria parameter, and the code uses introspection to determine which * fields are core and which are extensions (assuming it is a table that with extensions). The querying is extremely * flexible and dynamic, which means it is also not optimized ... use with care on large data sets! * * @param criteria * Provides the detail filter and sorting information * @param entityClass * The class of the data to be returned * @return List of result objects of type entityClass */ @Transactional public QueryResult<T> getData(Criteria criteria, Class<?> entityClass) { TableInfo tableInfo = TableInfo.create(entityClass); QueryResult<T> result = new QueryResult<>(); Session session = ((HibernateEntityManager) em).getSession(); StringBuilder sql = new StringBuilder(); if (StringUtils.isNotBlank(tableInfo.getExtTableName())) { sql.append("SELECT {filtered.*}, {extended.*} "); sql.append(", filtered." + tableInfo.getPkColumn() + " INDX FROM ("); } String baseSql = generateFilterQuery(criteria, tableInfo, result, true, true); result.setExectutedSql(baseSql); sql.append(baseSql); if (criteria.isPagingActive()) { sql.append(" LIMIT " + criteria.getFirstResults()); sql.append(", " + criteria.getPageSize()); } if (StringUtils.isNotBlank(tableInfo.getExtTableName())) { sql.append(") filtered "); sql.append(" left join " + tableInfo.getExtTableName() + " extended on (filtered." + tableInfo.getPkColumn() + " = extended." + tableInfo.getPkColumn() + ") "); } SQLQuery query = session.createSQLQuery(sql.toString()); if (StringUtils.isNotBlank(tableInfo.getExtTableName())) { query.addScalar("INDX"); // this scalar has to be here to workaround a hibernate bug. query.addEntity("filtered", tableInfo.getEntityClass()); query.addJoin("extended", "filtered." + tableInfo.getExtFieldName()); query.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE); } else if (StringUtils.isNotBlank(tableInfo.getTableName())) { query.addEntity("main", tableInfo.getEntityClass()); } else if (Map.class.isAssignableFrom(entityClass)) { query.setResultTransformer(AliasToEntityStringMapResultTransformer.INSTANCE); } else { query.setResultTransformer(new IgnoringCaseAliasToBeanResultTransformer(tableInfo.getEntityClass())); } for (String key : criteria.getParameters().keys()) { result.queryParameters.put(key, criteria.getParameters().get(key)); } query.setProperties(result.queryParameters); List<T> rows = query.list(); result.setRows(rows); if (!criteria.isPagingActive()) { result.setTotalRowCount(rows.size()); } else { StringBuilder countSql = new StringBuilder(); countSql.append("select count(*) cnt from ("); countSql.append(generateFilterQuery(criteria, tableInfo, result, false, false)); countSql.append(") c"); SQLQuery countQuery = session.createSQLQuery(countSql.toString()); countQuery.addScalar("cnt", StandardBasicTypes.INTEGER); // this scalar has to be here to workaround a hibernate // bug. countQuery.setProperties(result.queryParameters); Integer count = (Integer) countQuery.uniqueResult(); result.setTotalRowCount(count); } return result; }
@Test public void testFetchMode(){ JazzDetachedCriteria criteria = JazzDetachedCriteria.forClass(QuestionnaireVO.class); //criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); ResultTransformer rt = DistinctRootEntityResultTransformer.INSTANCE; criteria.setResultTransformer(rt); criteria.add(Restrictions.eq("PK", 1l)); criteria.enableFetchProfile("questinario_com_questoes"); criteria.enableFetchProfile("questao_com_alternativas"); List<QuestionnaireVO> questinnaires = hibernateTemplate.findByCriteria(criteria); //criteria.disableFetchProfile("questinario_com_questoes"); //questinnaires = hibernateTemplate.findByCriteria(criteria); for (QuestionnaireVO questionnaireVO : questinnaires) { System.out.println("\t "+questionnaireVO.getDescription()); Collection<QuestionVO> questions = questionnaireVO.getQuestions(); for (QuestionVO questionVO : questions) { System.out.println("\t\t "+questionVO.getDescription()); Set<AbstractCriterionVO> criterions = questionVO.getCriterionVOs(); for (AbstractCriterionVO alternativeVO : criterions) { String x = alternativeVO==null?"":alternativeVO.getDescription(); System.out.println("\t\t\t "+alternativeVO+" "+x); } } System.out.println(questionnaireVO); } }