List of usage examples for org.hibernate SQLQuery addEntity
SQLQuery<T> addEntity(String tableAlias, Class entityType);
From source file:boeken.BoekenDao.java
List getBoekenVanSchrijver(String schrijver) { SQLQuery query = sessie.createSQLQuery(""); query.addEntity("BOEKEN", Boek.class);//entities toevoegen juist?? query.setString(0, schrijver);//from w w w . ja va 2s. co m return query.list(); }
From source file:com.duroty.application.files.manager.FilesManager.java
License:Open Source License
/** * DOCUMENT ME!// www . j av a2s. c om * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param folderName DOCUMENT ME! * @param page DOCUMENT ME! * @param messagesByPage DOCUMENT ME! * @param order DOCUMENT ME! * @param orderType DOCUMENT ME! * * @return DOCUMENT ME! * * @throws FilesException DOCUMENT ME! */ public Vector getFiles(Session hsession, String repositoryName, String folderName, int label, int page, int messagesByPage, int order, String orderType) throws FilesException { Vector files = new Vector(); try { Users user = getUser(hsession, repositoryName); Locale locale = new Locale(user.getUseLanguage()); TimeZone timeZone = TimeZone.getDefault(); Date now = new Date(); Calendar calendar = Calendar.getInstance(timeZone, locale); calendar.setTime(now); SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale); SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale); SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale); Query hquery = null; String[] folderNameList = new String[0]; try { folderName = parseFolder(folderName); folderNameList = new String[] { folderName }; if (folderName.equals(this.folderAll) || folderName.equals(this.folderHidden)) { folderNameList = new String[] { this.folderAll, this.folderDraft, this.folderHidden, this.folderImportant, this.folderInbox, this.folderSent }; } } catch (Exception ex) { } if ((folderNameList.length == 0) && (label <= 0)) { hquery = hsession.getNamedQuery("attachments"); } else if ((folderNameList.length > 0) && (label <= 0)) { hquery = hsession.getNamedQuery("attachments-by-folder"); } else if ((folderNameList.length == 0) && (label > 0)) { hquery = hsession.getNamedQuery("attachments-by-label"); } else if ((folderNameList.length > 0) && (label > 0)) { hquery = hsession.getNamedQuery("attachments-by-folder-label"); } String aux = hquery.getQueryString(); switch (order) { case ORDER_BY_SIZE: if (orderType.equals("ASC")) { aux += " order by att_size asc"; } else { aux += " order by att_size desc"; } break; case ORDER_BY_DATE: if (orderType.equals("ASC")) { aux += " order by mes_date asc"; } else { aux += " order by mes_date desc"; } break; case ORDER_BY_TYPE: if (orderType.equals("ASC")) { aux += " order by att_content_type asc"; } else { aux += " order by att_content_type desc"; } break; default: if (!orderType.equals("ASC")) { aux += " order by att_name desc"; } else { aux += " order by att_name asc"; } break; } SQLQuery h2query = hsession.createSQLQuery(aux); if ((folderNameList.length == 0) && (label <= 0)) { h2query.setParameterList("no_boxes", new String[] { this.folderTrash, this.folderChat, this.folderSpam, FOLDER_DELETE }); h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint()); } else if ((folderNameList.length > 0) && (label <= 0)) { h2query.setParameterList("boxes", folderNameList); h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint()); } else if ((folderNameList.length == 0) && (label > 0)) { h2query.setInteger("label", label); h2query.setParameterList("no_boxes", new String[] { this.folderTrash, this.folderChat, this.folderSpam, FOLDER_DELETE }); h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint()); } else if ((folderNameList.length > 0) && (label > 0)) { h2query.setInteger("label", label); h2query.setParameterList("boxes", folderNameList); h2query.setInteger("user", getUser(hsession, repositoryName).getUseIdint()); } h2query.setFirstResult(page * messagesByPage); h2query.setMaxResults(messagesByPage); h2query.addEntity("testo", AttachmentWithDate.class); ScrollableResults scroll = h2query.scroll(); while (scroll.next()) { AttachmentWithDate attachment = (AttachmentWithDate) scroll.get(0); AttachmentObj obj = new AttachmentObj(); obj.setContentType(attachment.getAttContentType()); Date date = attachment.getAttDate(); if (date != null) { Calendar calendar2 = Calendar.getInstance(timeZone, locale); calendar2.setTime(date); if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) { obj.setDateStr(formatter2.format(calendar2.getTime())); } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) { obj.setDateStr(formatter1.format(calendar2.getTime())); } else { obj.setDateStr(formatter3.format(calendar2.getTime())); } } obj.setDate(date); obj.setDate(date); obj.setIdint(attachment.getAttIdint()); obj.setName(attachment.getAttName()); obj.setPart(attachment.getAttPart()); int size = attachment.getAttSize(); size /= 1024; if (size > 1024) { size /= 1024; obj.setSize(size + " MB"); } else { obj.setSize(((size > 0) ? (size + "") : "<1") + " kB"); } String extension = (String) this.extensions.get(attachment.getAttContentType()); if (StringUtils.isBlank(extension)) { extension = "generic"; } obj.setExtension(extension); Message message = attachment.getMessage(); if (message.isMesFlagged()) { obj.setFlagged(true); } else { obj.setFlagged(false); } if (message.getLabMeses() != null) { Iterator it = message.getLabMeses().iterator(); StringBuffer lab = new StringBuffer(); while (it.hasNext()) { if (lab.length() > 0) { lab.append(", "); } LabMes labMes = (LabMes) it.next(); lab.append(labMes.getId().getLabel().getLabName()); } if (lab.length() > 0) { obj.setLabel(lab.toString()); } else { } } obj.setBox(message.getMesBox()); obj.setMid(message.getMesName()); files.addElement(obj); } return files; } catch (Exception e) { throw new FilesException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.duroty.application.mail.manager.MailManager.java
License:Open Source License
/** * DOCUMENT ME!/*w ww . j a v a 2 s . co m*/ * * @param hsession DOCUMENT ME! * @param repositoryName DOCUMENT ME! * @param label DOCUMENT ME! * @param page DOCUMENT ME! * @param messagesByPage DOCUMENT ME! * @param order DOCUMENT ME! * @param orderType DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MailException DOCUMENT ME! */ public Vector getMessages(Session hsession, String repositoryName, Label label, int page, int messagesByPage, int order, String orderType) throws MailException { Vector messages = new Vector(); try { Users user = getUser(hsession, repositoryName); Locale locale = new Locale(user.getUseLanguage()); TimeZone timeZone = TimeZone.getDefault(); Date now = new Date(); Calendar calendar = Calendar.getInstance(timeZone, locale); calendar.setTime(now); SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale); SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale); SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale); Query hquery = hsession.getNamedQuery("messages-by-label"); String aux = hquery.getQueryString(); switch (order) { case ORDER_BY_IMPORTANT: if (orderType.equals("ASC")) { aux += " order by mes_flagged asc"; } else { aux += " order by mes_flagged desc"; } break; case ORDER_BY_ADDRESS: if (orderType.equals("ASC")) { aux += " order by mes_from asc"; } else { aux += " order by mes_from desc"; } break; case ORDER_BY_SIZE: if (orderType.equals("ASC")) { aux += " order by mes_size asc"; } else { aux += " order by mes_size desc"; } break; case ORDER_BY_SUBJECT: if (orderType.equals("ASC")) { aux += " order by mes_subject asc"; } else { aux += " order by mes_subject desc"; } break; case ORDER_BY_DATE: if (orderType.equals("ASC")) { aux += " order by mes_date asc"; } else { aux += " order by mes_date desc"; } break; case ORDER_BY_UNREAD: if (orderType.equals("ASC")) { aux += " order by mes_recent asc"; } else { aux += " order by mes_recent desc"; } break; default: aux += " order by mes_date desc"; break; } SQLQuery h2query = hsession.createSQLQuery(aux); h2query.addEntity("i", Message.class); h2query.setInteger("label", label.getLabIdint()); h2query.setInteger("user", user.getUseIdint()); h2query.setString("folderTrash", this.folderTrash); h2query.setString("folderSpam", this.folderSpam); h2query.setString("folderDelete", FOLDER_DELETE); h2query.setFirstResult(page * messagesByPage); h2query.setMaxResults(messagesByPage); ScrollableResults scroll = h2query.scroll(); while (scroll.next()) { Message message = (Message) scroll.get(0); MessageObj obj = new MessageObj(message.getMesName()); obj.setBox(message.getMesBox()); obj.setFrom(message.getMesFrom()); if ((message.getAttachments() != null) && (message.getAttachments().size() > 0)) { obj.setHasAttachment(true); } else { obj.setHasAttachment(false); } int size = message.getMesSize(); size /= 1024; if (size > 1024) { size /= 1024; obj.setSize(size + " MB"); } else { obj.setSize(((size > 0) ? (size + "") : "<1") + " kB"); } if (message.getMesBox().equals(folderSent)) { try { obj.setEmail(message.getMesTo()); } catch (Exception e) { obj.setEmail("unknown to"); } } else { obj.setEmail(message.getMesFrom()); } Date date = message.getMesDate(); if (date != null) { Calendar calendar2 = Calendar.getInstance(timeZone, locale); calendar2.setTime(date); if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)) && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) { obj.setDateStr(formatter2.format(calendar2.getTime())); } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) { obj.setDateStr(formatter1.format(calendar2.getTime())); } else { obj.setDateStr(formatter3.format(calendar2.getTime())); } } obj.setDate(date); if (message.getLabMeses() != null) { Iterator it = message.getLabMeses().iterator(); StringBuffer buff = new StringBuffer(); while (it.hasNext()) { if (buff.length() > 0) { buff.append(", "); } LabMes labMes = (LabMes) it.next(); buff.append(labMes.getId().getLabel().getLabName()); } obj.setLabel(buff.toString()); } try { if (StringUtils.isBlank(message.getMesSubject())) { obj.setSubject("(no subject)"); } else { obj.setSubject(message.getMesSubject()); } } catch (Exception ex) { obj.setSubject("(no subject)"); } if (message.isMesFlagged()) { obj.setFlagged(true); } else { obj.setFlagged(false); } if (message.isMesRecent()) { obj.setRecent(true); } else { obj.setRecent(false); } String priority = "normal"; if (MessageUtilities.isHighPriority(message.getMesHeaders())) { priority = "high"; } else if (MessageUtilities.isLowPriority(message.getMesHeaders())) { priority = "low"; } obj.setPriority(priority); messages.addElement(obj); } return messages; } catch (Exception e) { throw new MailException(e); } finally { GeneralOperations.closeHibernateSession(hsession); } }
From source file:com.liferay.samplehibernate.util.FoodItemUtil.java
License:Open Source License
public static List getFoodItems() throws Exception { Session session = null;/* www .j av a2 s. com*/ try { session = HibernateUtil.openSession(); session.beginTransaction(); SQLQuery q = session.createSQLQuery(_GET_FOOD_ITEMS); q.addEntity("FoodItem", FoodItem.class); List list = q.list(); session.getTransaction().commit(); return list; } catch (Exception e) { throw new Exception(e); } finally { HibernateUtil.closeSession(session); } }
From source file:com.mysema.query.jpa.hibernate.sql.AbstractHibernateSQLQuery.java
License:Apache License
private Query createQuery(String queryString) { logQuery(queryString);/*from www. ja v a 2 s. c o m*/ org.hibernate.SQLQuery query = session.createSQLQuery(queryString); // set constants HibernateUtil.setConstants(query, constants, queryMixin.getMetadata().getParams()); // set entity paths for (Path<?> path : entityPaths) { query.addEntity(path.toString(), path.getType()); } // set result transformer, if projection is an EConstructor instance List<? extends Expression<?>> projection = queryMixin.getMetadata().getProjection(); if (projection.size() == 1 && projection.get(0) instanceof FactoryExpression) { query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection.get(0))); } 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 (readOnly != null) { query.setReadOnly(readOnly); } return query; }
From source file:com.querydsl.jpa.hibernate.sql.AbstractHibernateSQLQuery.java
License:Apache License
private Query createQuery(boolean forCount) { NativeSQLSerializer serializer = (NativeSQLSerializer) serialize(forCount); String queryString = serializer.toString(); logQuery(queryString, serializer.getConstantToLabel()); org.hibernate.SQLQuery query = session.createSQLQuery(queryString); // set constants HibernateUtil.setConstants(query, serializer.getConstantToLabel(), queryMixin.getMetadata().getParams()); if (!forCount) { ListMultimap<Expression<?>, String> aliases = serializer.getAliases(); Set<String> used = Sets.newHashSet(); // set entity paths Expression<?> projection = queryMixin.getMetadata().getProjection(); if (projection instanceof FactoryExpression) { for (Expression<?> expr : ((FactoryExpression<?>) projection).getArgs()) { if (isEntityExpression(expr)) { query.addEntity(extractEntityExpression(expr).toString(), expr.getType()); } else if (aliases.containsKey(expr)) { for (String scalar : aliases.get(expr)) { if (!used.contains(scalar)) { query.addScalar(scalar); used.add(scalar); break; }/* w ww .java 2 s . c o m*/ } } } } else if (isEntityExpression(projection)) { query.addEntity(extractEntityExpression(projection).toString(), projection.getType()); } else if (aliases.containsKey(projection)) { for (String scalar : aliases.get(projection)) { if (!used.contains(scalar)) { query.addScalar(scalar); used.add(scalar); break; } } } // set result transformer, if projection is a FactoryExpression instance if (projection instanceof FactoryExpression) { query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection)); } } 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 (readOnly != null) { query.setReadOnly(readOnly); } return query; }
From source file:com.quix.aia.cn.imo.utilities.ImoUtilityData.java
License:Open Source License
public void updateCitySscOfficeBaseonAgenter() { Session session = null;/*from w w w .jav a2 s. c om*/ Transaction tx; ArrayList list = null; try { session = HibernateFactory.openSession(); tx = session.beginTransaction(); /*session.createSQLQuery("UPADTE T_CITY SET STATUS=INACTIVE WHERE CITY_NAME NOT IN (SELECT CITYCODE FROM AGENTER)").executeUpdate(); session.createSQLQuery("UPADTE T_SSC SET STATUS=INACTIVE WHERE SSC_NAME NOT IN (SELECT SSC FROM AGENTER)").executeUpdate(); session.createSQLQuery("UPADTE T_OFFICE SET STATUS=INACTIVE WHERE OFFICE_NAME NOT IN (SELECT OFFCOD FROM AGENTER)").executeUpdate(); */ /*Query query =session.createQuery("UPDATE City set status=false where cityName not in (select city from AamData )"); query =session.createQuery("UPDATE Ssc set status=false where sscName not in (select ssc from AamData )"); query.executeUpdate(); query =session.createQuery("UPDATE Office set status=false where officeName not in (select officeCode from AamData )"); query.executeUpdate(); */ SQLQuery query = session.createSQLQuery( "SELECT {s.*} FROM T_CITY {s} WHERE STATUS=1 and CITY_NAME NOT IN (SELECT CITYCODE FROM AGENTER)"); ArrayList<City> entities = (ArrayList<City>) query.addEntity("s", City.class).list(); if (entities.size() > 0) { for (City city : entities) { city.setStatus(false); session.update(city); } } query = session.createSQLQuery( "SELECT {s.*} FROM T_SSC {s} WHERE STATUS=1 and SSC_NAME NOT IN (SELECT SSC FROM AGENTER)"); ArrayList<Ssc> sscList = (ArrayList<Ssc>) query.addEntity("s", Ssc.class).list(); if (sscList.size() > 0) { for (Ssc ssc : sscList) { ssc.setStatus(false); session.update(ssc); } } query = session.createSQLQuery( "SELECT {s.*} FROM T_OFFICE {s} WHERE STATUS=1 and OFFICE_NAME NOT IN (SELECT OFFCOD FROM AGENTER)"); ArrayList<Office> officeList = (ArrayList<Office>) query.addEntity("s", Office.class).list(); if (officeList.size() > 0) { for (Office office : officeList) { office.setStatus(false); session.update(office); } } tx.commit(); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); LogsMaintenance logsMain = new LogsMaintenance(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); logsMain.insertLogs("IMOUtilityData", Level.SEVERE + "", errors.toString()); } finally { try { HibernateFactory.close(session); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } } }
From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java
License:Apache License
public Map<Long, List<ModificationForPipeline>> findModificationsForPipelineIds(final List<Long> pipelineIds) { final int MODIFICATION = 0; final int RELEVANT_PIPELINE_ID = 1; final int RELEVANT_PIPELINE_NAME = 2; final int MATERIAL_TYPE = 3; final int MATERIAL_FINGERPRINT = 4; //noinspection unchecked return (Map<Long, List<ModificationForPipeline>>) getHibernateTemplate() .execute((HibernateCallback) session -> { if (pipelineIds.isEmpty()) { return new HashMap<Long, List<ModificationForPipeline>>(); }//from w ww.j a v a 2 s . c o m Map<PipelineId, Set<Long>> relevantToLookedUpMap = relevantToLookedUpDependencyMap(session, pipelineIds); SQLQuery query = session.createSQLQuery( "SELECT mods.*, pmr.pipelineId as pmrPipelineId, p.name as pmrPipelineName, m.type as materialType, m.fingerprint as fingerprint" + " FROM modifications mods " + " INNER JOIN pipelineMaterialRevisions pmr ON (mods.id >= pmr.fromRevisionId AND mods.id <= pmr.toRevisionId) AND mods.materialId = pmr.materialId " + " INNER JOIN pipelines p ON pmr.pipelineId = p.id" + " INNER JOIN materials m ON mods.materialId = m.id" + " WHERE pmr.pipelineId IN (:ids)"); @SuppressWarnings({ "unchecked" }) List<Object[]> allModifications = query.addEntity("mods", Modification.class) .addScalar("pmrPipelineId", new LongType()) .addScalar("pmrPipelineName", new StringType()) .addScalar("materialType", new StringType()).addScalar("fingerprint", new StringType()) .setParameterList("ids", relevantToLookedUpMap.keySet().stream() .map(PipelineId::getPipelineId).collect(Collectors.toList())) .list(); Map<Long, List<ModificationForPipeline>> modificationsForPipeline = new HashMap<>(); CollectionUtil.CollectionValueMap<Long, ModificationForPipeline> modsForPipeline = CollectionUtil .collectionValMap(modificationsForPipeline, new CollectionUtil.ArrayList<>()); for (Object[] modAndPmr : allModifications) { Modification mod = (Modification) modAndPmr[MODIFICATION]; Long relevantPipelineId = (Long) modAndPmr[RELEVANT_PIPELINE_ID]; String relevantPipelineName = (String) modAndPmr[RELEVANT_PIPELINE_NAME]; String materialType = (String) modAndPmr[MATERIAL_TYPE]; String materialFingerprint = (String) modAndPmr[MATERIAL_FINGERPRINT]; PipelineId relevantPipeline = new PipelineId(relevantPipelineName, relevantPipelineId); Set<Long> longs = relevantToLookedUpMap.get(relevantPipeline); for (Long lookedUpPipeline : longs) { modsForPipeline.put(lookedUpPipeline, new ModificationForPipeline(relevantPipeline, mod, materialType, materialFingerprint)); } } return modificationsForPipeline; }); }
From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java
License:Apache License
@SuppressWarnings("unchecked") public List<MatchedRevision> findRevisionsMatching(final MaterialConfig materialConfig, final String searchString) { return (List<MatchedRevision>) getHibernateTemplate().execute((HibernateCallback) session -> { String sql = "SELECT m.*" + " FROM modifications AS m" + " INNER JOIN materials mat ON mat.id = m.materialId" + " WHERE mat.fingerprint = :finger_print" + " AND (m.revision || ' ' || COALESCE(m.username, '') || ' ' || COALESCE(m.comment, '') LIKE :search_string OR m.pipelineLabel LIKE :search_string)" + " ORDER BY m.id DESC" + " LIMIT 5"; SQLQuery query = session.createSQLQuery(sql); query.addEntity("m", Modification.class); Material material = materialConfigConverter.toMaterial(materialConfig); query.setString("finger_print", material.getFingerprint()); query.setString("search_string", "%" + searchString + "%"); final List<MatchedRevision> list = new ArrayList<>(); for (Modification mod : (List<Modification>) query.list()) { list.add(material.createMatchedRevision(mod, searchString)); }//from ww w . j a va2s. co m return list; }); }
From source file:com.userweave.csv.questionnaire.RrtToCsv.java
License:Open Source License
@SuppressWarnings("unchecked") private List<Object[]> getRrtResult(RrtConfigurationEntity configuration) { QueryObject queryObject = rrtResultDao.createQuery(configuration, null); queryObject.setResult("{result.*}, se.id as surveyexec_id"); SQLQuery q = new QueryTemplate(queryObject).createSqlQuery(getCurrentSession()); q.addEntity("result", RrtResult.class); q.addScalar("surveyexec_id", Hibernate.INTEGER); return q.list(); }