// Ensure close is called on the stateful session correctly.
  @Test
  public void testStatefulClose() {

    SessionFactory sessionFactory = createMock(SessionFactory.class);
    Session session = createMock(Session.class);
    Query scrollableResults = createNiceMock(Query.class);
    HibernateCursorItemReader<Foo> itemReader = new HibernateCursorItemReader<Foo>();
    itemReader.setSessionFactory(sessionFactory);
    itemReader.setQueryString("testQuery");
    itemReader.setUseStatelessSession(false);

    expect(sessionFactory.openSession()).andReturn(session);
    expect(session.createQuery("testQuery")).andReturn(scrollableResults);
    expect(scrollableResults.setFetchSize(0)).andReturn(scrollableResults);
    expect(session.close()).andReturn(null);

    replay(sessionFactory);
    replay(session);
    replay(scrollableResults);

    itemReader.open(new ExecutionContext());
    itemReader.close();

    verify(sessionFactory);
    verify(session);
  }
  @Test
  @TestForIssue(jiraKey = "HHH-3694")
  public void testResultTransformerIsAppliedToScrollableResults() throws Exception {
    Session s = openSession();
    Transaction tx = s.beginTransaction();

    PartnerA a = new PartnerA();
    a.setName("Partner A");
    PartnerB b = new PartnerB();
    b.setName("Partner B");
    Contract obj1 = new Contract();
    obj1.setName("Contract");
    obj1.setA(a);
    obj1.setB(b);
    s.save(a);
    s.save(b);
    s.save(obj1);

    tx.commit();
    s.close();

    s = openSession();

    Query q = s.getNamedQuery(Contract.class.getName() + ".testQuery");
    q.setFetchSize(100);
    q.setResultTransformer(
        new ResultTransformer() {

          private static final long serialVersionUID = -5815434828170704822L;

          public Object transformTuple(Object[] arg0, String[] arg1) {
            // return only the PartnerA object from the query
            return arg0[1];
          }

          @SuppressWarnings("unchecked")
          public List transformList(List arg0) {
            return arg0;
          }
        });
    ScrollableResults sr = q.scroll();
    // HANA supports only ResultSet.TYPE_FORWARD_ONLY and
    // does not support java.sql.ResultSet.first()
    if (getDialect() instanceof AbstractHANADialect) {
      sr.next();
    } else {
      sr.first();
    }

    Object[] row = sr.get();
    assertEquals(1, row.length);
    Object obj = row[0];
    assertTrue(obj instanceof PartnerA);
    PartnerA obj2 = (PartnerA) obj;
    assertEquals("Partner A", obj2.getName());
    s.close();
  }
  private Query createQuery(
      String queryString, @Nullable QueryModifiers modifiers, boolean forCount) {
    Query query = session.createQuery(queryString);
    HibernateUtil.setConstants(query, getConstants(), getMetadata().getParams());
    if (fetchSize > 0) {
      query.setFetchSize(fetchSize);
    }
    if (timeout > 0) {
      query.setTimeout(timeout);
    }
    if (cacheable != null) {
      query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
      query.setCacheRegion(cacheRegion);
    }
    if (comment != null) {
      query.setComment(comment);
    }
    if (readOnly != null) {
      query.setReadOnly(readOnly);
    }
    for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
      query.setLockMode(entry.getKey().toString(), entry.getValue());
    }
    if (flushMode != null) {
      query.setFlushMode(flushMode);
    }

    if (modifiers != null && modifiers.isRestricting()) {
      if (modifiers.getLimit() != null) {
        query.setMaxResults(modifiers.getLimit().intValue());
      }
      if (modifiers.getOffset() != null) {
        query.setFirstResult(modifiers.getOffset().intValue());
      }
    }

    // set transformer, if necessary
    List<? extends Expression<?>> projection = getMetadata().getProjection();
    if (projection.size() == 1 && !forCount) {
      Expression<?> expr = projection.get(0);
      if (expr instanceof FactoryExpression<?>) {
        query.setResultTransformer(
            new FactoryExpressionTransformer((FactoryExpression<?>) projection.get(0)));
      }
    } else if (!forCount) {
      FactoryExpression<?> proj = FactoryExpressionUtils.wrap(projection);
      if (proj != null) {
        query.setResultTransformer(new FactoryExpressionTransformer(proj));
      }
    }
    return query;
  }
 @Override
 public void open() {
   currentRecordNumber = 0;
   Query hibernateQuery = session.createQuery(query);
   hibernateQuery.setReadOnly(true);
   if (maxResults >= 1) {
     hibernateQuery.setMaxResults(maxResults);
   }
   if (fetchSize >= 1) {
     hibernateQuery.setFetchSize(fetchSize);
   }
   scrollableResults = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
 }
  /**
   * Execute the selection query in the database
   *
   * @return The query result. Each Object is a cell content.
   *     <p>The cell contents use database types (date,int,string...), keep in mind in case of
   *     future conversions/castings.
   * @throws InterruptedException
   */
  @SuppressWarnings("unchecked")
  public List<List<Object>> executeQuery() throws InterruptedException {

    List<List<Object>> rowsList = new ArrayList<List<Object>>();
    Query query;

    if (!session.isConnected()) {
      resetConnection();
    }

    if (sqlSourceHelper.isCustomQuerySet()) {

      query = session.createSQLQuery(sqlSourceHelper.buildQuery());

      if (sqlSourceHelper.getMaxRows() != 0) {
        query = query.setMaxResults(sqlSourceHelper.getMaxRows());
      }
    } else {
      query =
          session
              .createSQLQuery(sqlSourceHelper.getQuery())
              .setFirstResult(Integer.parseInt(sqlSourceHelper.getCurrentIndex()));

      if (sqlSourceHelper.getMaxRows() != 0) {
        query = query.setMaxResults(sqlSourceHelper.getMaxRows());
      }
    }

    try {
      rowsList =
          query
              .setFetchSize(sqlSourceHelper.getMaxRows())
              .setResultTransformer(Transformers.TO_LIST)
              .list();
    } catch (Exception e) {
      resetConnection();
    }

    if (!rowsList.isEmpty()) {
      if (sqlSourceHelper.isCustomQuerySet()) {
        sqlSourceHelper.setCurrentIndex(rowsList.get(rowsList.size() - 1).get(0).toString());
      } else {
        sqlSourceHelper.setCurrentIndex(
            Integer.toString(
                (Integer.parseInt(sqlSourceHelper.getCurrentIndex()) + rowsList.size())));
      }
    }

    return rowsList;
  }
 @Override
 public List<ThesaurusConcept> getConceptsWoNotes(String idThesaurus, int startIndex, int limit) {
   Query query =
       getCurrentSession()
           .createSQLQuery(
               "select c.* "
                   + "from thesaurus_concept c  "
                   + "left join note n on c.identifier = n.conceptid  "
                   + "where c.thesaurusid=:pthesaurusid"
                   + " and n.identifier is null")
           .addEntity(ThesaurusConcept.class);
   query.setParameter("pthesaurusid", idThesaurus);
   query.setFirstResult(startIndex);
   query.setFetchSize(limit);
   query.setMaxResults(limit);
   return (List<ThesaurusConcept>) query.list();
 }
  /**
   * Creates the Hibernate query object.
   *
   * <p>If the value of the {@link
   * JRHibernateQueryExecuterFactory#PARAMETER_HIBERNATE_FILTER_COLLECTION
   * PARAMETER_HIBERNATE_FILTER_COLLECTION} is not null, then a filter query is created using the
   * value of the parameter as the collection.
   *
   * @param queryString the query string
   */
  protected synchronized void createQuery(String queryString) {
    if (log.isDebugEnabled()) {
      log.debug("HQL query: " + queryString);
    }

    Object filterCollection =
        getParameterValue(JRHibernateQueryExecuterFactory.PARAMETER_HIBERNATE_FILTER_COLLECTION);
    if (filterCollection == null) {
      query = session.createQuery(queryString);
    } else {
      query = session.createFilter(filterCollection, queryString);
    }
    query.setReadOnly(true);

    int fetchSize =
        JRProperties.getIntegerProperty(
            dataset, JRJdbcQueryExecuterFactory.PROPERTY_JDBC_FETCH_SIZE, 0);
    if (fetchSize != 0) {
      query.setFetchSize(fetchSize);
    }

    setParameters();
  }
示例#8
0
 protected void applyFetchSize(int fetchSize) {
   query.setFetchSize(fetchSize);
 }