Example usage for javax.persistence Query setParameter

List of usage examples for javax.persistence Query setParameter

Introduction

In this page you can find the example usage for javax.persistence Query setParameter.

Prototype

Query setParameter(int position, Object value);

Source Link

Document

Bind an argument value to a positional parameter.

Usage

From source file:edu.iu.m.news.dao.NewsDaoImpl.java

@Override
public NewsSource getNewsSourceById(String rssShortCode) {
    Query query = entityManager.createQuery(
            "select r from MaintRss r where r.shortCode like :rssShortCode and r.type like 'NEWS'");
    query.setParameter("rssShortCode", rssShortCode);
    try {/*from ww  w. j  a  v a2s. co m*/
        return convertMaintRssToNewsSource((MaintRss) query.getSingleResult());
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.opens.tanaguru.entity.dao.tgol.contract.TanaguruSurveyContractDAOImpl.java

/**
 * Native sql query ://from   w w  w  .java 2s . c  o m
 * SELECT c.Label, c.Url, wrs.Raw_Mark FROM TGSI_USER AS u
 *       INNER JOIN TGSI_CONTRACT AS c ON ( u.Id_User = c.USER_Id_User )
 *       INNER JOIN TGSI_ACT AS a ON
 *       ( c.Id_Contract = a.CONTRACT_Id_Contract AND a.End_Date = (SELECT End_Date FROM TGSI_ACT WHERE CONTRACT_Id_Contract = a.CONTRACT_Id_Contract ORDER BY End_Date DESC LIMIT 1 ) )
 *       INNER JOIN TGSI_ACT_WEB_RESOURCE awr ON ( a.Id_Act = awr.ACT_Id_Act )
 *       INNER JOIN WEB_RESOURCE_STATISTICS AS wrs ON ( awr.WEB_RESOURCE_Id_Web_Resource = wrs.Id_Web_Resource )
 *       WHERE u.Email1 = :listUser
 *       ORDER BY wrs.Raw_Mark  DESC
 *       LIMIT :nbOfResults;
 *
 * @param listUser
 * @param nbOfResults
 * @return
 *      a collection of initialised ContractResult instances
 */
@Override
public Collection<ContractResult> findTopNContractsFromListUser(String listUser, int nbOfResults) {
    StringBuilder queryString = new StringBuilder();
    queryString.append(FIND_TOP_N_CONTRACT_QUERY);
    Query query = entityManager.createNativeQuery(queryString.toString());
    query.setParameter("listUser", listUser);
    query.setParameter("nbOfResults", nbOfResults);
    Collection<ContractResult> contractResultSet = new LinkedHashSet<ContractResult>();
    List<Object[]> result = null;
    try {
        result = (List<Object[]>) query.getResultList();
    } catch (NoResultException nre) {
        return contractResultSet;
    }
    for (Object[] obj : result) {
        ContractResult cr = contractResultFactory.createContractResult((String) obj[0], // label
                (String) obj[1], //url
                ((Float) obj[2]).intValue(), //mark
                ((BigInteger) obj[3]).longValue()); //webResourceId
        contractResultSet.add(cr);
    }
    return contractResultSet;
}

From source file:br.com.binarti.simplesearchexpr.builders.jpql.JPQLWhereClause.java

/**
 * Apply parameter values to a query.//from www.j  a  v a2  s  .  c  o m
 * @param query The query to receive parameter values
 */
public void applyParameters(Query query) {
    if (parameters.size() > 0) {
        for (Entry<String, Object> param : parameters.entrySet()) {
            query.setParameter(param.getKey(), param.getValue());
        }
    }
}

From source file:com.doculibre.constellio.services.FeaturedLinkServicesImpl.java

@Override
public FeaturedLink suggest(String text, RecordCollection collection) {
    FeaturedLink suggestion;/*from  ww w .  j a  va 2  s. c  o  m*/
    EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();

    String analyzedText;
    try {
        analyzedText = AnalyzerUtils.analyze(text, collection);
    } catch (Exception e) {
        analyzedText = null;
    }

    if (StringUtils.isNotBlank(analyzedText)) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT FL.id FROM FeaturedLink FL, FeaturedLink_KeywordsAnalyzed FLK, RecordCollection RC");
        sql.append(" WHERE FLK.FeaturedLink_id=FL.id AND FL.RecordCollection_id=RC.id");
        sql.append(" AND RC.id=? AND FLK.keyword=?");

        Query sqlQuery = entityManager.createNativeQuery(sql.toString());
        sqlQuery.setMaxResults(1);
        sqlQuery.setParameter(1, collection.getId());
        sqlQuery.setParameter(2, analyzedText);

        try {
            BigInteger featuredLinkId = (BigInteger) sqlQuery.getSingleResult();
            suggestion = get(featuredLinkId.longValue());
        } catch (NoResultException e) {
            suggestion = null;
        }
    } else {
        suggestion = null;
    }
    return suggestion;
}

From source file:com.solidmaps.webapp.dao.LicensePCDAO.java

public LicensePCEntity findByCompanyExpirationDate(Integer idCompany, Calendar dateExpiration) {

    StringBuilder sb = new StringBuilder();
    sb.append("from LicensePCEntity e where e.company.idCompany =:idCompany ");
    sb.append("and e.isActive =:active ");
    sb.append("and e.dateExpiration >= :dateExpiration ");
    sb.append("order by dateExpiration desc ");

    Query query = super.getEm().createQuery(sb.toString());

    query.setParameter("idCompany", idCompany);
    query.setParameter("dateExpiration", dateExpiration);
    query.setParameter("active", Boolean.TRUE);

    @SuppressWarnings("unchecked")
    List<LicensePCEntity> list = query.getResultList();

    if (list != null && !list.isEmpty()) {
        return list.get(0);
    }/*from  w ww. j  ava  2  s  .c o m*/

    // TODO Refatorar essa Gambi aqui. Jogar pra uma Service

    // Se no possui Licena vigente, verifica se a ltima est protocolada
    LicensePCEntity lastProtocoled = this.findByLastProtocoled(idCompany);
    if (lastProtocoled != null && StringUtils.isNotBlank(lastProtocoled.getProtocolRenovation())) {
        return lastProtocoled;
    }

    return null;

}

From source file:com.mothsoft.alexis.dao.ModelDaoImpl.java

@Override
public Model findByUserAndName(Long userId, String name) {
    final Query query = this.em.createQuery("SELECT m FROM Model m WHERE userId = :userId AND name = :name");
    query.setParameter("userId", userId);
    query.setParameter("name", name);

    @SuppressWarnings("unchecked")
    final List<Model> models = (List<Model>) query.getResultList();

    if (models == null || models.size() != 1) {
        return null;
    } else {//ww w.ja va  2 s .c  om
        return models.get(0);
    }
}

From source file:com.healthcit.cacure.dao.QuestionTableDao.java

@Transactional(propagation = Propagation.REQUIRED)
public void reorderQuestions(Long sourceQuestionId, Long targetQuestionId, boolean before) {

    Validate.notNull(sourceQuestionId);//from w  w w .jav  a 2  s  . c  o m
    Validate.notNull(targetQuestionId);

    if (sourceQuestionId.equals(targetQuestionId)) {
        return;
    }

    Query query = em.createQuery("SELECT ord, form.id FROM TableQuestion WHERE id = :id");

    Object[] result = (Object[]) query.setParameter("id", sourceQuestionId).getSingleResult();
    int sOrd = (Integer) result[0];
    long sFormId = (Long) result[1];

    result = (Object[]) query.setParameter("id", targetQuestionId).getSingleResult();
    int tOrd = (Integer) result[0];
    long tFormId = (Long) result[1];

    Validate.isTrue(sFormId == tFormId); //reorder only inside one form

    if (sOrd == tOrd || (before && sOrd == tOrd - 1) || (!before && sOrd == tOrd + 1)) {
        return;
    } else if (sOrd < tOrd) {
        em.createQuery("UPDATE TableQuestion SET ord = ord - 1 WHERE ord > :sOrd and ord "
                + (before ? "<" : "<=") + " :tOrd and form.id = :formId").setParameter("sOrd", sOrd)
                .setParameter("tOrd", tOrd).setParameter("formId", sFormId).executeUpdate();
        em.createQuery("UPDATE TableQuestion SET ord = :tOrd WHERE id = :qId")
                .setParameter("qId", sourceQuestionId).setParameter("tOrd", before ? tOrd - 1 : tOrd)
                .executeUpdate();
    } else if (sOrd > tOrd) {
        em.createQuery("UPDATE TableQuestion SET ord = ord + 1 WHERE ord < :sOrd and ord "
                + (before ? ">=" : ">") + " :tOrd and form.id = :formId").setParameter("sOrd", sOrd)
                .setParameter("tOrd", tOrd).setParameter("formId", sFormId).executeUpdate();
        em.createQuery("UPDATE TableQuestion SET ord = :tOrd WHERE id = :qId")
                .setParameter("qId", sourceQuestionId).setParameter("tOrd", before ? tOrd : tOrd + 1)
                .executeUpdate();
    }
}

From source file:com.june.app.board.repository.jpa.BoardRepositoryImpl.java

@Override
@SuppressWarnings("unchecked")
public Collection<Board> boardList(Board vo) {
    String queryString = "SELECT board FROM Board board WHERE board.useYn ='Y'";
    int bbsId = vo.getBbsId();
    if (bbsId > 0) {
        queryString += "and board.bbsId = :bbsId";
    }/* w  ww.j a  v a 2  s.co  m*/
    Query query = this.em.createQuery(queryString);
    if (bbsId > 0) {
        query.setParameter("bbsId", bbsId);
    }

    return query.getResultList();
}

From source file:com.appdynamicspilot.persistence.CartPersistence.java

@Transactional
public void deleteAllCartItems(Long userId) {
    EntityManager em = getEntityManager();
    EntityTransaction txn = em.getTransaction();
    txn.begin();//from w  w  w. j  a  v  a  2 s .  co m
    Query q = em.createQuery("DELETE FROM Cart c where c.user.id=:id");
    q.setParameter("id", userId);
    q.executeUpdate();
    txn.commit();
}

From source file:com.mothsoft.alexis.dao.ModelDaoImpl.java

@Override
public Long findAndMarkOne(ModelState current, ModelState toSet) {
    final Query query = this.em.createQuery("SELECT m FROM Model m WHERE m.state =:state ORDER BY m.id ASC");
    query.setParameter("state", current);
    query.setMaxResults(1);// ww w .  jav  a 2s. com

    @SuppressWarnings("unchecked")
    final List<Model> models = (List<Model>) query.getResultList();

    if (models == null || models.isEmpty()) {
        return null;
    } else {
        final Model model = models.get(0);
        model.setState(toSet);
        return model.getId();
    }
}