Exemplo n.º 1
0
 public static <T> void setResultTransformer(final Class<T> entityClass, final Query query) {
   if (entityClass != null) {
     if (entityClass.equals(Map.class)) {
       query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
     } else {
       query.setResultTransformer(Transformers.aliasToBean(entityClass));
     }
   }
 }
  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;
  }
Exemplo n.º 3
0
 /**
  * Get time information from a named query
  *
  * @param seriesId Series id
  * @param seriesMinMaxTransformer Hibernate result transformator for min/max time value
  * @param session Hibernate Session
  * @return Time period
  */
 private TimePeriod getTimePeriodFromNamedQuery(
     long seriesId, SeriesMinMaxTransformer seriesMinMaxTransformer, Session session) {
   Query namedQuery = session.getNamedQuery(SQL_QUERY_GET_DATA_AVAILABILITY_FOR_SERIES);
   namedQuery.setParameter(SeriesObservationInfo.SERIES, seriesId);
   LOGGER.debug("QUERY getTimePeriodFromNamedQuery(series) with NamedQuery: {}", namedQuery);
   namedQuery.setResultTransformer(seriesMinMaxTransformer);
   return (TimePeriod) namedQuery.uniqueResult();
 }
Exemplo n.º 4
0
 private List<?> executeNamedQuery(GetDataAvailabilityRequest req, Session session) {
   final boolean features = req.isSetFeaturesOfInterest();
   final boolean observableProperties = req.isSetObservedProperties();
   final boolean procedures = req.isSetProcedures();
   String namedQueryName = null;
   Map<String, Collection<String>> parameter = Maps.newHashMap();
   // all
   if (features && observableProperties && procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_FEATURES_PROCEDURES_OBSERVED_PROPERTIES;
     parameter.put(FEATURES, req.getFeaturesOfInterest());
     parameter.put(OBSERVABLE_PROPERTIES, req.getObservedProperties());
     parameter.put(PROCEDURES, req.getProcedures());
   }
   // observableProperties and procedures
   else if (!features && observableProperties && procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_PROCEDURES_OBSERVED_PROPERTIES;
     parameter.put(OBSERVABLE_PROPERTIES, req.getObservedProperties());
     parameter.put(PROCEDURES, req.getProcedures());
   }
   // only observableProperties
   else if (!features && observableProperties && !procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_OBSERVED_PROPERTIES;
     parameter.put(OBSERVABLE_PROPERTIES, req.getObservedProperties());
   }
   // only procedures
   else if (!features && !observableProperties && procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_PROCEDURES;
     parameter.put(PROCEDURES, req.getProcedures());
   }
   // features and observableProperties
   else if (features && observableProperties && !procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_FEATURES_OBSERVED_PROPERTIES;
     parameter.put(FEATURES, req.getFeaturesOfInterest());
     parameter.put(OBSERVABLE_PROPERTIES, req.getObservedProperties());
   }
   // features and procedures
   else if (features && !observableProperties && procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_FEATURES_PROCEDURES;
     parameter.put(FEATURES, req.getFeaturesOfInterest());
     parameter.put(PROCEDURES, req.getProcedures());
   }
   // only features
   else if (features && !observableProperties && procedures) {
     namedQueryName = SQL_QUERY_GET_DATA_AVAILABILITY_FOR_FEATURES;
     parameter.put(FEATURES, req.getFeaturesOfInterest());
   }
   if (StringHelper.isNotEmpty(namedQueryName)) {
     Query namedQuery = session.getNamedQuery(namedQueryName);
     for (String key : parameter.keySet()) {
       namedQuery.setParameterList(key, parameter.get(key));
     }
     LOGGER.debug(
         "QUERY getProceduresForFeatureOfInterest(feature) with NamedQuery: {}", namedQuery);
     namedQuery.setResultTransformer(new DataAvailabilityTransformer(session));
     return namedQuery.list();
   }
   return Lists.newLinkedList();
 }
  @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();
  }
Exemplo n.º 6
0
 public List<Map<String, Object>> findBySqlList(String sql) {
   List<Map<String, Object>> list = null;
   if (StringUtils.isNotBlank(sql)) {
     Query query = getDefaultSession().createSQLQuery(sql);
     query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
     list = query.list();
   }
   return list;
 }
 public List<Arquivo> getArquivos(Professor object) {
   String hqlQuery = "SELECT arquivo FROM Arquivo arquivo WHERE professor.id = " + object.getId();
   Query query = dao.getHibernateSession().createQuery(hqlQuery);
   query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   log.info("query.list*(");
   List<Arquivo> listaArquivosComParam = query.list();
   log.info("teste" + listaArquivosComParam);
   log.info("Tamanho da Lista: " + listaArquivosComParam.size());
   return listaArquivosComParam;
 }
  @SuppressWarnings("unchecked")
  public static List<Game> getCompleteGamesList() {
    List<Game> games = new ArrayList<Game>();

    Session session = HibernateUtil.getSession();
    Transaction transaction = session.beginTransaction();
    try {
      Query query = session.createQuery(Constants.HQL.GET_GAMES_COMPLETE);
      games = (List<Game>) query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
      transaction.commit();
    } catch (Exception e) {
      transaction.rollback();
      e.printStackTrace();
    }
    session.close();

    return games;
  }
  public <T> TypedQuery<T> createQuery(
      String jpaqlString, Class<T> resultClass, Selection selection, Options options) {
    try {
      org.hibernate.Query hqlQuery = getSession().createQuery(jpaqlString);

      if (options.getValueHandlers() == null) {
        options.getResultMetadataValidator().validate(hqlQuery.getReturnTypes());
      }

      // determine if we need a result transformer
      List tupleElements =
          Tuple.class.equals(resultClass)
              ? ((CompoundSelectionImpl<Tuple>) selection).getCompoundSelectionItems()
              : null;
      if (options.getValueHandlers() != null || tupleElements != null) {
        hqlQuery.setResultTransformer(
            new CriteriaQueryTransformer(options.getValueHandlers(), tupleElements));
      }
      return new QueryImpl<T>(hqlQuery, this, options.getNamedParameterExplicitTypes());
    } catch (HibernateException he) {
      throw convert(he);
    }
  }
Exemplo n.º 10
0
  public void testMappedAliasStrategy() {
    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");
    Serializable orgId = s.save(jboss);
    Serializable orgId2 = s.save(ifa);
    s.save(gavin);
    s.save(emp);
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    Query namedQuery = s.getNamedQuery("AllEmploymentAsMapped");
    List list = namedQuery.list();
    assertEquals(1, list.size());
    Employment emp2 = (Employment) list.get(0);
    assertEquals(emp2.getEmploymentId(), emp.getEmploymentId());
    assertEquals(emp2.getStartDate().getDate(), emp.getStartDate().getDate());
    assertEquals(emp2.getEndDate(), emp.getEndDate());
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    Query sqlQuery = s.getNamedQuery("EmploymentAndPerson");
    sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    list = sqlQuery.list();
    assertEquals(1, list.size());
    Object res = list.get(0);
    assertClassAssignability(res.getClass(), Map.class);
    Map m = (Map) res;
    assertEquals(2, m.size());
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    sqlQuery = s.getNamedQuery("organizationreturnproperty");
    sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    list = sqlQuery.list();
    assertEquals(2, list.size());
    m = (Map) list.get(0);
    assertEquals(2, m.size());
    assertTrue(m.containsKey("org"));
    assertTrue(m.containsKey("emp"));
    assertClassAssignability(m.get("org").getClass(), Organization.class);
    if (jboss.getId() == ((Organization) m.get("org")).getId()) {
      assertClassAssignability(m.get("emp").getClass(), Employment.class);
    }
    Map m2 = (Map) list.get(1);
    assertEquals(2, m.size());
    assertTrue(m2.containsKey("org"));
    assertTrue(m2.containsKey("emp"));
    assertClassAssignability(m2.get("org").getClass(), Organization.class);
    if (jboss.getId() == ((Organization) m2.get("org")).getId()) {
      assertClassAssignability(m2.get("emp").getClass(), Employment.class);
    }
    t.commit();
    s.close();

    s = openSession();
    t = s.beginTransaction();
    namedQuery = s.getNamedQuery("EmploymentAndPerson");
    list = namedQuery.list();
    assertEquals(1, list.size());
    Object[] objs = (Object[]) list.get(0);
    assertEquals(2, objs.length);
    emp2 = (Employment) objs[0];
    gavin = (Person) objs[1];
    s.delete(emp2);
    s.delete(jboss);
    s.delete(gavin);
    s.delete(ifa);
    t.commit();
    s.close();
  }
Exemplo n.º 11
0
  /**
   * 根据回复内容,推送给对应老师或家长
   *
   * @param msg
   * @return
   */
  public void pushMsg_replay_to_classNews_to_teacherOrParent(String type_uuid, String msg)
      throws Exception {

    Session session = this.nSimpleHibernateDao.getSession();
    String sql = " SELECT t1.uuid,t1.create_useruuid,t1.usertype,t1.groupuuid";
    sql += " FROM px_classnews t1 ";
    sql += " where t1.uuid='" + type_uuid + "'  ";
    Query query = session.createSQLQuery(sql);
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List<Map> list = query.list();

    if (list.size() == 0) return;

    Map obj = list.get(0);
    if (obj.get("usertype") == null) {
      logger.error("px_classnews usertype is null,uuid" + type_uuid);
      return;
    }

    if ("1".equals((obj.get("usertype").toString()))) {
      // 家长,暂时不开发通知
      return;
    }

    boolean isSendPushMsg = true;
    List users = new ArrayList();
    users.add(obj.get("create_useruuid"));

    List<PushMessage> listPushMessage =
        this.getPushMessageList(SystemConstants.common_type_hudong, type_uuid, users);
    PushMessage pushMessage = null;
    if (listPushMessage.size() > 0) {
      pushMessage = listPushMessage.get(0);
    }
    //		PushMessage pushMessage = (PushMessage) this.nSimpleHibernateDao
    //				.getObjectByAttribute(PushMessage.class, "rel_uuid", type_uuid);
    if (pushMessage == null) {
      pushMessage = new PushMessage();
      pushMessage.setCount(1);
    } else { // 已经发过消息的情况下,只修改对应的内容.不新加数据.
      if (SystemConstants.Read_flag_0.equals(pushMessage.getIsread())) { // 未读情况下,推送消息不在发送.
        isSendPushMsg = false;
        if (pushMessage.getCount() == null) { // 计数.
          pushMessage.setCount(1);
        } else {
          pushMessage.setCount(pushMessage.getCount() + 1);
        }
      } else { //
        pushMessage.setCount(1);
      }
    }
    pushMessage.setGroup_uuid((String) obj.get("groupuuid"));
    pushMessage.setRevice_useruuid((String) obj.get("create_useruuid"));
    pushMessage.setType(SystemConstants.common_type_hudong);
    pushMessage.setRel_uuid(type_uuid);
    pushMessage.setTitle("互动(" + pushMessage.getCount() + ")");
    pushMessage.setMessage(PxStringUtil.getSubString(msg, 128));
    pushMessage.setCreate_time(TimeUtils.getCurrentTimestamp());
    pushMessage.setIsread(SystemConstants.Read_flag_0);

    this.nSimpleHibernateDao.save(pushMessage);
    if (isSendPushMsg) { // 不重复发送消息
      if ("1".equals((obj.get("usertype").toString()))) {
        // 家长
        this.pushMsgToAPPIservice.pushMsg_to_parent_app(
            pushMessage.getRevice_useruuid(), pushMessage.getTitle(), msg);
      } else {
        // 老师
        this.pushMsgToAPPIservice.pushMsg_to_teacher_app(
            pushMessage.getRevice_useruuid(), pushMessage.getTitle(), msg);
      }
    }
  }
Exemplo n.º 12
0
 /** 为Query添加distinct transformer. 预加载关联对象的HQL会引起主对象重复, 需要进行distinct处理. */
 public Query distinct(Query query) {
   query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
   return query;
 }
  public List<Arquivo> getArquivos(
      Integer materia, Integer ano, Integer semestre, Integer professor, String turno)
      throws IntranetException {
    log.info("Executando DAO");
    log.info("ANO: " + ano);
    log.info("SEMESTRE: " + semestre);
    log.info("MATERIA: " + materia);
    log.info("Professor: " + professor);
    log.info("Turno: " + turno);
    if ((ano == null || ano == -1)
        && (semestre == null || semestre == -1)
        && (materia == null || materia == -1)
        && (professor == null || professor == -1)
        && (StringUtils.isNullOrEmpty(turno) || turno.equals("-1"))) {

      log.info("Recuperando arquivos");
      String hqlQuery =
          "SELECT arquivo FROM Arquivo arquivo, IN(arquivo.disciplinaLetiva.disciplina.cursos) curso";
      Query query = dao.getHibernateSession().createQuery(hqlQuery);
      query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

      List<Arquivo> listaArquivosComParam = query.list();
      return listaArquivosComParam;
    }

    boolean first = true;
    String hqlQuery =
        "SELECT arquivo FROM Arquivo arquivo, IN(arquivo.disciplinaLetiva.disciplina.cursos) curso WHERE ";

    if (ano != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.ano = " + ano;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.ano = " + ano;
      }
    }

    if (semestre != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.semestre = " + semestre;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.semestre = " + semestre;
      }
    }

    if (materia != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.disciplina.id = " + materia;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.disciplina.id = " + materia;
      }
    }

    if (professor != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.professor.id = " + professor;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.professor.id = " + professor;
      }
    }

    log.info("Iniciando filtro");
    if (StringUtils.isNotNull(turno) && !turno.equals("-1")) {
      log.info("Entrou em turno");
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.turno = '" + turno + "'";
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.turno = '" + turno + "'";
      }
    }
    log.info("QUERY: " + hqlQuery);
    Query query = dao.getHibernateSession().createQuery(hqlQuery);
    query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    List<Arquivo> listaArquivosComParam = query.list();
    return listaArquivosComParam;
  }
  @Override
  public List<Arquivo> getArquivos(
      Integer materia, Integer ano, Integer semestre, Integer professor) throws IntranetException {
    log.info("Executando DAO");
    log.info("ANO: " + ano);
    log.info("SEMESTRE: " + semestre);
    log.info("MATERIA: " + materia);
    log.info("Professor: " + professor);

    if ((ano == null || ano == -1)
        && (semestre == null || semestre == -1)
        && (materia == null || materia == -1)
        && (professor == null || professor == -1)) {

      log.info("Recuperando arquivos");
      String hqlQuery =
          "SELECT arquivo FROM Arquivo arquivo, IN(arquivo.disciplinaLetiva.disciplina.cursos) curso";
      Query query = dao.getHibernateSession().createQuery(hqlQuery);
      query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

      List<Arquivo> listaArquivosComParam = query.list();
      return listaArquivosComParam;
    }

    boolean first = true;
    String hqlQuery =
        "SELECT arquivo FROM Arquivo arquivo, IN(arquivo.disciplinaLetiva.disciplina.cursos) curso WHERE ";

    if (ano != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.ano = " + ano;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.ano = " + ano;
      }
    }

    if (semestre != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.semestre = " + semestre;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.semestre = " + semestre;
      }
    }

    if (materia != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.disciplinaLetiva.disciplina.id = " + materia;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.disciplinaLetiva.disciplina.id = " + materia;
      }
    }

    if (professor != -1) {
      if (first) {
        hqlQuery = hqlQuery + "arquivo.professor.id = " + professor;
        first = false;
      } else {
        hqlQuery = hqlQuery + " AND arquivo.professor.id = " + professor;
      }
    }

    Query query = dao.getHibernateSession().createQuery(hqlQuery);
    query.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    List<Arquivo> listaArquivosComParam = query.list();
    return listaArquivosComParam;
  }