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:at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead.java

public static OnlineApplication getOnlineApplication(long dbid) {
    MiscUtil.assertNotNull(dbid, "OnlineApplictionID");
    Logger.trace("Getting OnlineApplication with DBID " + dbid + " from database.");

    List result;/*  ww w  .  j  ava  2 s .c o m*/
    EntityManager session = ConfigurationDBUtils.getCurrentSession();

    javax.persistence.Query query = session.createQuery(QUERIES.get("getOnlineApplicationWithDBID"));
    //query.setParameter("id", id+"%");
    query.setParameter("id", dbid);
    result = query.getResultList();

    Logger.trace("Found entries: " + result.size());

    if (result.size() == 0) {
        Logger.trace("No entries found.");
        return null;
    }

    return (OnlineApplication) result.get(0);
}

From source file:at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead.java

public static OnlineApplication getOnlineApplication(String id) {
    MiscUtil.assertNotNull(id, "OnlineApplictionID");
    Logger.trace("Getting OnlineApplication with ID " + id + " from database.");

    List result;/*from w  w w. jav a  2 s .co m*/
    EntityManager session = ConfigurationDBUtils.getCurrentSession();

    javax.persistence.Query query = session.createQuery(QUERIES.get("getOnlineApplicationWithID"));
    //query.setParameter("id", id+"%");
    query.setParameter("id", id);
    result = query.getResultList();

    Logger.trace("Found entries: " + result.size());

    if (result.size() == 0) {
        Logger.trace("No entries found.");
        return null;
    }

    if (result.size() > 1) {
        Logger.warn("OAIdentifier match to more then one DB-entry!");
        return null;
    }

    return (OnlineApplication) result.get(0);
}

From source file:at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead.java

public static OnlineApplication getActiveOnlineApplication(String id) {
    MiscUtil.assertNotNull(id, "OnlineApplictionID");
    Logger.trace("Getting OnlineApplication with ID " + id + " from database.");

    List result;//from  w  w w. j ava2 s . c  o m
    EntityManager session = ConfigurationDBUtils.getCurrentSession();

    javax.persistence.Query query = session.createQuery(QUERIES.get("getActiveOnlineApplicationWithID"));
    //query.setParameter("id", id+"%");
    query.setParameter("id", StringEscapeUtils.escapeHtml4(id));
    result = query.getResultList();

    Logger.trace("Found entries: " + result.size());

    if (result.size() == 0) {
        Logger.debug("No entries found.");
        return null;
    }

    if (result.size() > 1) {
        Logger.warn("OAIdentifier match to more then one DB-entry!");
        return null;
    }

    return (OnlineApplication) result.get(0);
}

From source file:models.SkillTag.java

public static Page<SkillTagListVo> listTagByCate(Long cateId, Integer page, Integer start, Integer limit,
        String searchText) {/*ww w .j ava2s . c  o  m*/
    String hql1 = "select count(s) from SkillTag s where s.industryId=? and s.id<>?";
    if (searchText != null && !"".equals(searchText)) {
        hql1 += " and (s.tagName like ? or s.tagNameEn like ?)";
    }
    Query query1 = JPA.em().createQuery(hql1);
    query1.setParameter(1, cateId);
    query1.setParameter(2, cateId);
    if (searchText != null && !"".equals(searchText)) {
        query1.setParameter(3, "%" + searchText + "%");
        query1.setParameter(4, "%" + searchText + "%");
    }
    Long total = (Long) query1.getSingleResult();

    String hql2 = "from SkillTag s left join fetch s.industry where s.industryId=? and s.id<>?";
    if (searchText != null && !"".equals(searchText)) {
        hql2 += " and (s.tagName like ? or s.tagNameEn like ?)";
    }
    hql2 += " order by s.seq asc";

    Query query2 = JPA.em().createQuery(hql2);
    query2.setParameter(1, cateId);
    query2.setParameter(2, cateId);
    if (searchText != null && !"".equals(searchText)) {
        query2.setParameter(3, "%" + searchText + "%");
        query2.setParameter(4, "%" + searchText + "%");
    }

    List<SkillTag> skillTags = query2.setFirstResult(start).setMaxResults(limit).getResultList();
    Page<SkillTagListVo> p = new Page<SkillTagListVo>();
    p.setTotal(total);

    List<SkillTagListVo> sklvs = new ArrayList<SkillTagListVo>();
    for (SkillTag skillTag : skillTags) {
        SkillTagListVo sklv = new SkillTagListVo();
        sklv.setId(skillTag.id);
        if (skillTag.industry != null) {
            sklv.setIndustryId(skillTag.industry.id);
            sklv.setIndustryName(skillTag.industry.tagName);
        }
        sklv.setHits(skillTag.hits);
        sklv.setTagNameEn(skillTag.tagNameEn);
        sklv.setTagName(skillTag.tagName);
        sklv.setSeq(skillTag.seq);
        sklv.setTagType(skillTag.tagType);
        sklvs.add(sklv);
    }
    p.setData(sklvs);
    return p;
}

From source file:models.ModuleVersion.java

public static SortedMap<String, SortedSet<ModuleVersion>> findDependants(String moduleName, String version) {
    String query = "SELECT d.version, v FROM ModuleVersion v JOIN v.dependencies d LEFT JOIN FETCH v.module WHERE d.name=:name";
    if (version != null && !version.isEmpty()) {
        query += " AND d.version=:version";
    }// ww w  .  j  a  v  a 2  s .  c om
    Query jpa = JPA.em().createQuery(query).setParameter("name", moduleName);
    if (version != null && !version.isEmpty()) {
        jpa.setParameter("version", version);
    }
    List<Object[]> results = jpa.getResultList();

    Comparator<String> versionComparator = new Comparator<String>() {
        @Override
        public int compare(String v1, String v2) {
            return Util.compareVersions(v1, v2);
        }
    };

    Comparator<ModuleVersion> dependantComparator = new Comparator<ModuleVersion>() {
        @Override
        public int compare(ModuleVersion v1, ModuleVersion v2) {
            int result = v1.module.name.compareTo(v2.module.name);
            if (result == 0) {
                result = Util.compareVersions(v1.version, v2.version);
            }
            return result;
        }
    };

    SortedMap<String, SortedSet<ModuleVersion>> dependantsMap = new TreeMap<String, SortedSet<ModuleVersion>>(
            versionComparator);
    for (Object[] result : results) {
        String ver = (String) result[0];
        ModuleVersion dependant = (ModuleVersion) result[1];

        SortedSet<ModuleVersion> dependants = dependantsMap.get(ver);
        if (dependants == null) {
            dependants = new TreeSet<ModuleVersion>(dependantComparator);
            dependantsMap.put(ver, dependants);
        }
        dependants.add(dependant);
    }

    return dependantsMap;
}

From source file:entity.files.SYSFilesTools.java

/**
 * <code>putFile(String)</code> speichert eine Datei auf dem FTP Server ab und erstellt eine SYSFiles EntityBean. Die Methode geht dabei wie folgt vor:
 * <ol>/*from w ww  .ja v a 2 s.  co m*/
 * <li>Zuerst wird der MD5 der zu speichernden Datei berechnet.</li>
 * <li>Anhand dieser MD5 Signatur wird ermittelt, ob es schon einen entsprechenden Eintrag in der Datenbank gibt.
 * <ul>
 * <li>Wenn ja, dann wird einfach der PK zurckgegeben. Nochmal speichern braucht man das ja nicht. <b>RETURN</b></li>
 * <li>Wenn nicht, dann geht die Bearbeitung weiter.</li>
 * </ul>
 * <li>Erstellen einer SYSFiles EB</li>
 * <li>Senden der Datei an den FTP Server</li>
 * <li>Wenn die letzten beiden Schritte erfolgreich waren, dann wird die neue EB als Ergebnis zurck gegeben. null, bei Fehler.</li>
 * </ol>
 *
 * @param file File Objekt der zu speichernden Datei
 * @return EB der neuen Datei. null bei Fehler.
 */
private static SYSFiles putFile(EntityManager em, FileTransferClient ftp, File file) throws Exception {
    SYSFiles sysfile = null;

    String md5 = SYSTools.getMD5Checksum(file);
    Query query = em.createQuery("SELECT s FROM SYSFiles s WHERE s.md5 = :md5");
    query.setParameter("md5", md5);

    ArrayList<SYSFiles> alreadyExistingFiles = new ArrayList<SYSFiles>(query.getResultList());

    // Gibts die Datei schon ?
    if (alreadyExistingFiles.isEmpty()) { // nein, noch nicht
        sysfile = em.merge(new SYSFiles(file.getName(), md5, new Date(file.lastModified()), file.length(),
                OPDE.getLogin().getUser()));
        //            FileInputStream fis = new FileInputStream(file);
        ftp.uploadFile(file.getPath(), sysfile.getRemoteFilename());

        //            ftp.storeF.storeFile(file.getPath(),sysfile.getRemoteFilename());
        OPDE.info(
                SYSTools.xx("misc.msg.upload") + ": " + sysfile.getFilename() + " (" + sysfile.getMd5() + ")");
        //            fis.close();
    } else { // Ansonsten die bestehende Datei zurckgeben

        sysfile = alreadyExistingFiles.get(0);

        // Does the User own this file already ?
        //            for (SYSFiles mySYSfile : alreadyExistingFiles) {
        //                if (mySYSfile.getResident().equals(resident)) {
        //                    sysfile = mySYSfile;
        //                    break;
        //                }
        //            }
        //            if (sysfile == null) {
        //                sysfile = em.merge(new SYSFiles(file.getName(), md5, new Date(file.lastModified()), file.length(), OPDE.getLogin().getUser(), resident));
        //            }
    }

    return sysfile;
}

From source file:models.Expert.java

@SuppressWarnings("unchecked")
public static List<Expert> getPartExpert(String p, Integer pageSize, Long i, String s, String cf, String ssf,
        String ef, String gf, String o, String ot) {
    StringBuffer joinBuffer = new StringBuffer("from Expert e join fetch e.user u ");
    StringBuffer whereStr = new StringBuffer("where (e.userName is not null and u.isEnable = true) ");
    StringBuffer orderStr = new StringBuffer();
    if (null != i) {
        joinBuffer.append("left join fetch e.inTags i ");
        whereStr.append("and i.id = :industryId ");
    }//from  www  .  j  av a2 s. com
    if (StringUtils.isNotBlank(o)) {
        if (o.equals("averageScore"))
            orderStr.append(" order by e.averageScore desc,e.joinDate desc");
        if (o.equals("dealNum"))
            orderStr.append(" order by e.dealNum desc,e.joinDate desc");
        if (o.equals("commentNum")) {
            orderStr.append(" order by e.commentNum desc,e.joinDate desc");
        }
    } else {
        orderStr.append(" order by e.joinDate desc");
    }
    if (StringUtils.isNotBlank(cf))
        whereStr.append(" and e.country = '").append(cf).append("'");
    if (StringUtils.isNotBlank(ef)) {
        if (ef.equals("0")) {
            whereStr.append(" and e.payType = 0 ");
        } else if (ef.equals("1")) {
            whereStr.append(" and e.payType = 1 ");
        }
    }
    if (StringUtils.isNotBlank(gf))
        whereStr.append(" and e.gender = ").append(gf);
    if (s != null) {
        whereStr.append(" and e.skillsTags like :skilltags ");
    }

    joinBuffer.append(whereStr).append(orderStr);
    Query query = JPA.em().createQuery(joinBuffer.toString());
    if (null != i) {
        query.setParameter("industryId", i);
    }

    if (s != null) {
        return (List<Expert>) query.setParameter("skilltags", "%" + s + "%")
                .setFirstResult((Integer.parseInt(p) - 1) * pageSize).setMaxResults(pageSize).getResultList();
    } else {
        return (List<Expert>) query.setFirstResult((Integer.parseInt(p) - 1) * pageSize).setMaxResults(pageSize)
                .getResultList();
    }

}

From source file:com.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString/*from   w w  w  . j a  va  2 s.  c  o  m*/
 * @param q
 */
public static void setQueryParameters(String queryString, HashMap<String, String> paramsMap, Query q) {
    KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
    Set<Parameter<?>> parameters = kq.getParameters();
    for (String paramName : paramsMap.keySet()) {
        String value = paramsMap.get(paramName);

        if (StringUtils.isNumeric(paramName)) {
            for (Parameter param : parameters) {
                if (param.getPosition() == Integer.parseInt(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(Integer.parseInt(paramName), paramValue);
                    break;
                }
            }
        } else {
            for (Parameter param : parameters) {
                if (param.getName().equals(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    if (paramName.equalsIgnoreCase("firstResult")) {
                        q.setFirstResult(Integer.parseInt((String) paramValue));
                    } else if (paramName.equalsIgnoreCase("maxResult")) {
                        q.setMaxResults(Integer.parseInt((String) paramValue));
                    } else {
                        q.setParameter(paramName, paramValue);
                    }
                    break;
                }
            }

        }
    }
}

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

@Transactional(readOnly = true)
@SuppressWarnings("unchecked")
public List<Role> getUserRoles(UserCredentials user) {
    String jpql = "select u.roles from UserCredentials u where u = :user";
    Query query = em.createQuery(jpql);
    query.setParameter("user", user);
    return query.getResultList();
}

From source file:com.sshdemo.common.security.web.authentication.rememberme.dao.RememberMeTokenDAO.java

public void removeUserTokens(final String username) {
    String hql = "Delete From RememberMeToken o Where o.username=:username ";

    Query query = this.getEntityManager().createQuery(hql);
    query.setParameter("username", username);

    query.executeUpdate();/*from   w w w . ja v  a 2 s .c o  m*/
}