@Override @SuppressWarnings("unchecked") public List<VoteStatsDTO> getStatisticsBySession(Long toolContentId) { SQLQuery query = getSession().createSQLQuery(GET_STATISTICS); query.addScalar("sessionUid", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE) .addScalar("countUsersComplete", IntegerType.INSTANCE).setLong("contentId", toolContentId) .setResultTransformer(Transformers.aliasToBean(VoteStatsDTO.class)); return query.list(); }
@SuppressWarnings("rawtypes") @Override public Object[] getStatsMarksForLeaders(Long toolContentId) { Query query = getSession().createSQLQuery(FIND_MARK_STATS_FOR_LEADERS) .addScalar("min_grade", FloatType.INSTANCE) .addScalar("avg_grade", FloatType.INSTANCE) .addScalar("max_grade", FloatType.INSTANCE) .addScalar("num_complete", IntegerType.INSTANCE); query.setLong("toolContentId", toolContentId); List list = query.list(); if ((list == null) || (list.size() == 0)) { return null; } else { return (Object[]) list.get(0); } }
@Override @SuppressWarnings("deprecation") public Serializable disassemble(CollectionPersister persister) throws HibernateException { final Type elementType = persister.getElementType(); final String indexNodeName = getIndexAttributeName( persister ); final List elements = element.elements( persister.getElementNodeName() ); final int length = elements.size(); final Serializable[] result = new Serializable[length]; for ( int i=0; i<length; i++ ) { final Element elem = (Element) elements.get( i ); final Object object = elementType.fromXMLNode( elem, persister.getFactory() ); final Integer index = IntegerType.INSTANCE.fromString( getIndex( elem, indexNodeName, i ) ); result[index] = elementType.disassemble( object, getSession(), null ); } return result; }
@Override public Object[] getStatsMarksForLeaders(Long toolContentId) { Query query = getSession().createSQLQuery(FIND_MARK_STATS) .addScalar("min_grade", FloatType.INSTANCE) .addScalar("avg_grade", FloatType.INSTANCE) .addScalar("max_grade", FloatType.INSTANCE) .addScalar("num_complete", IntegerType.INSTANCE); query.setLong("toolContentId", toolContentId); @SuppressWarnings("rawtypes") List list = query.list(); if ((list == null) || (list.size() == 0)) { return null; } else { return (Object[]) list.get(0); } }
@SuppressWarnings({ "unchecked" }) private SortedSet<Comment> getNextThreadByThreadIdNewestFirst(final Long rootTopicId, final Long previousThreadMessageId, Integer numberOfThreads, Integer sortBy, Integer userId) { // the search to get to the top level is quite light, so get just the uids // then build a complete set. List<Number> threadUidList = null; if (previousThreadMessageId == null || previousThreadMessageId == 0L) { threadUidList = getSession().createSQLQuery(SQL_QUERY_FIND_FIRST_THREAD_TOP_BY_UID) .setLong("rootUid", rootTopicId).setMaxResults(numberOfThreads).list(); } else { threadUidList = getSession().createSQLQuery(SQL_QUERY_FIND_NEXT_THREAD_TOP).setLong("rootUid", rootTopicId) .setLong("lastUid", previousThreadMessageId).setMaxResults(numberOfThreads).list(); } if (threadUidList != null && threadUidList.size() > 0) { SQLQuery query = getSession().createSQLQuery(SQL_QUERY_FIND_NEXT_THREAD_MESSAGES); query.addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("userId", userId != null ? userId : 0) .setParameterList("threadIds", threadUidList); List<Object[]> results = query.list(); return upgradeComments(results, sortBy); } return new TreeSet<Comment>(); }
@SuppressWarnings({ "unchecked" }) private SortedSet<Comment> getStickyByThreadIdNewestFirst(final Long rootTopicId, Integer sortBy, Integer userId) { // the search to get to the top level is quite light, so get just the uids // then build a complete set. List<Number> threadUidList = getSession().createSQLQuery(SQL_QUERY_FIND_STICKY_BY_UID) .setLong("rootUid", rootTopicId).list(); if (threadUidList != null && threadUidList.size() > 0) { SQLQuery query = getSession().createSQLQuery(SQL_QUERY_FIND_NEXT_THREAD_MESSAGES); query.addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("userId", userId != null ? userId : 0) .setParameterList("threadIds", threadUidList); List<Object[]> results = query.list(); return upgradeComments(results, sortBy); } return new TreeSet<Comment>(); }
@SuppressWarnings({ "unchecked" }) private SortedSet<Comment> getStickyByThreadIdLikes(final Long rootTopicId, Integer sortBy, String extraSortParam, Integer userId) { List<Object[]> topThreadObjects = getSession().createSQLQuery(SQL_QUERY_FIND_STICKY_BY_LIKES) .addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("rootUid", rootTopicId) .setLong("userId", userId != null ? userId : 0).list(); if (topThreadObjects != null && topThreadObjects.size() > 0) { // build the list of uids List<Number> threadUidList = new ArrayList<Number>(); for (Object[] rawObject : topThreadObjects) { Comment comment = (Comment) rawObject[0]; threadUidList.add(comment.getUid()); } SQLQuery query = getSession().createSQLQuery(SQL_QUERY_FIND_NEXT_THREAD_MESSAGES_REPLIES_ONLY); query.addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("userId", userId != null ? userId : 0) .setParameterList("threadIds", threadUidList); List<Object[]> results = query.list(); topThreadObjects.addAll(results); return upgradeComments(topThreadObjects, sortBy); } return new TreeSet<Comment>(); }
protected Object get(Class clazz, String id) { if (clazz.equals(String.class) || clazz.equals(StringType.class)) return id; if (clazz.equals(Character.class) || clazz.equals(CharacterType.class)) return (id == null || id.isEmpty() ? null : id.charAt(0)); if (clazz.equals(Byte.class) || clazz.equals(ByteType.class)) return Byte.valueOf(id); if (clazz.equals(Short.class) || clazz.equals(ShortType.class)) return Short.valueOf(id); if (clazz.equals(Integer.class) || clazz.equals(IntegerType.class)) return Integer.valueOf(id); if (clazz.equals(Long.class) || clazz.equals(LongType.class)) return Long.valueOf(id); if (clazz.equals(Float.class) || clazz.equals(FloatType.class)) return Float.valueOf(id); if (clazz.equals(Double.class) || clazz.equals(DoubleType.class)) return Double.valueOf(id); if (clazz.equals(Boolean.class) || clazz.equals(BooleanType.class)) return Boolean.valueOf(id); Map<String, Entity> entities = iEntities.get(clazz.getName()); if (entities != null) { Entity entity = entities.get(id); if (entity != null) return entity.getObject(); } for (Map.Entry<String, Map<String, Entity>> entry: iEntities.entrySet()) { Entity o = entry.getValue().get(id); if (o != null && clazz.isInstance(o.getObject())) return o.getObject(); } if (clazz.equals(Session.class)) return ((Entity)iEntities.get(Session.class.getName()).values().iterator().next()).getObject(); if (clazz.equals(Student.class)) return checkUnknown(clazz, id, iStudents.get(id)); if (iIsClone) return checkUnknown(clazz, id, iHibSession.get(clazz, clazz.equals(ItypeDesc.class) ? (Serializable) Integer.valueOf(id) : (Serializable) Long.valueOf(id))); return checkUnknown(clazz, id, null); }
/** * Tests, whether a page with the given pageID exists. * Trying to retrieve a pageID that does not exist in Wikipedia throws an exception. * * @param pageID A pageID. * @return True, if a page with that pageID exits, false otherwise. */ public boolean existsPage(int pageID) { // TODO carefully, this is a hack to provide a much quicker way to test whether a page exists. // Encoding the title in this way surpasses the normal way of creating a title first. // This should get a unit test to make sure the encoding function is in line with the title object. // Anyway, I do not like this hack :-| if (pageID < 0) { return false; } Session session = this.__getHibernateSession(); session.beginTransaction(); List returnList = session.createNativeQuery( "select p.id from PageMapLine as p where p.pageID = :pageId") .setParameter("pageId", pageID, IntegerType.INSTANCE) .list(); session.getTransaction().commit(); return returnList.size() != 0; }
/** * Get the hibernate ID to a given pageID of a category. * We need different methods for pages and categories here, as a page and a category can have the same ID. * * @param pageID A pageID that should be mapped to the corresponding hibernate ID. * @return The hibernateID of the page with pageID or -1, if the pageID is not valid */ protected long __getCategoryHibernateId(int pageID) { long hibernateID = -1; // first look in the id mapping cache if (idMapCategories.containsKey(pageID)) { return idMapCategories.get(pageID); } // The id was not found in the id mapping cache. // It may not be in the cahe or may not exist at all. Session session = this.__getHibernateSession(); session.beginTransaction(); Object retObjectPage = session.createQuery( "select cat.id from Category as cat where cat.pageId = :pageId") .setParameter("pageId", pageID, IntegerType.INSTANCE) .uniqueResult(); session.getTransaction().commit(); if (retObjectPage != null) { hibernateID = (Long) retObjectPage; // add it to the cache idMapCategories.put(pageID, hibernateID); } return hibernateID; }
private void addScalars(SQLQuery query) { query.addScalar("URI", StringType.INSTANCE); query.addScalar("foundTimestamp", LongType.INSTANCE); query.addScalar("canonicalTag", StringType.INSTANCE); query.addScalar("httpStatusCode", IntegerType.INSTANCE); query.addScalar("lastCrawledTimestamp", LongType.INSTANCE); query.addScalar("contentHashcode", StringType.INSTANCE); query.addScalar("backgroundId", ShortType.INSTANCE); query.addScalar("qualityScore", ShortType.INSTANCE); query.addScalar("spamScore", ShortType.INSTANCE); query.addScalar("readingLevel", ShortType.INSTANCE); query.addScalar("varietyTopicScore", ShortType.INSTANCE); query.addScalar("adScripts", ShortType.INSTANCE); query.addScalar("relevantImages", BooleanType.INSTANCE); query.addScalar("responseTime", IntegerType.INSTANCE); query.addScalar("pageSize", IntegerType.INSTANCE); query.addScalar("pageRank", DoubleType.INSTANCE); query.addScalar("qwLocale", StringType.INSTANCE); query.addScalar("onPageText", StringType.INSTANCE); query.addScalar("title", StringType.INSTANCE); query.addScalar("metaDescription", StringType.INSTANCE); query.addScalar("topicKeyword", StringType.INSTANCE); query.addScalar("robotsIndex", BooleanType.INSTANCE); query.addScalar("duplicateTitle", BooleanType.INSTANCE); query.addScalar("duplicateMetaDescription", BooleanType.INSTANCE); query.addScalar("duplicateContent", BooleanType.INSTANCE); query.addScalar("trailingSlashIssue", BooleanType.INSTANCE); query.addScalar("timeout", BooleanType.INSTANCE); query.addScalar("pagination", BooleanType.INSTANCE); query.addScalar("dcPrimary", BooleanType.INSTANCE); }
private void addScalars(SQLQuery query) { query.addScalar("resultFromTimestampMills", LongType.INSTANCE); query.addScalar("qualityScore", ShortType.INSTANCE); query.addScalar("totalLinks", LongType.INSTANCE); query.addScalar("internalURLs", LongType.INSTANCE); query.addScalar("internalNoindexURLs", LongType.INSTANCE); query.addScalar("internalIndexURLs", LongType.INSTANCE); query.addScalar("externalURLs", LongType.INSTANCE); query.addScalar("externalURLsDifferentDomains", LongType.INSTANCE); query.addScalar("crawledURLs", LongType.INSTANCE); query.addScalar("clientErrorURLs", LongType.INSTANCE); query.addScalar("timeoutURLs", LongType.INSTANCE); query.addScalar("redirectionURLs", LongType.INSTANCE); query.addScalar("serverErrorURLs", LongType.INSTANCE); query.addScalar("avgResponseTimeMills", IntegerType.INSTANCE); query.addScalar("medianResponseTimeMills", IntegerType.INSTANCE); query.addScalar("avgPageSize", LongType.INSTANCE); query.addScalar("totalCountOfRelevantKeywords", LongType.INSTANCE); query.addScalar("totalCountOfKeywords", LongType.INSTANCE); query.addScalar("avgReadingLevel", DoubleType.INSTANCE); query.addScalar("domainBrandName", StringType.INSTANCE); query.addScalar("homeDocument", StringType.INSTANCE); }
@SuppressWarnings("unchecked") @Override public Map<Integer, Integer> countTotalDownloadedItemsForCollectionIds(final List<Long> ids) { return (Map<Integer, Integer>) getHibernateTemplate().execute(new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException { String sql = " select c.collection_id as id, " + " sum(c.count) as count " + " from collection_log c " + " where c.collection_id in :ids " + " group by c.collection_id "; SQLQuery sqlQuery = session.createSQLQuery(sql); sqlQuery.addScalar("id", new IntegerType()); sqlQuery.addScalar("count", new IntegerType()); sqlQuery.setParameterList("ids", ids); List<Object[]> list = sqlQuery.list(); Map<Integer, Integer> result = new HashMap<Integer, Integer>(); for (Object[] row : list) { result.put((Integer) row[0], (Integer) row[1]); } return result; } }); }
@Override public Number getUserWebFormFileMaxNum(String userId, String xmlSchema, String fileName, char numDelim, char extensionDelim) { String fileNameSearchCriteria; String maxProjection; int lastIndexOfDot = fileName.lastIndexOf(extensionDelim); if (lastIndexOfDot > 0) { fileNameSearchCriteria = fileName.substring(0, lastIndexOfDot) + numDelim + "%" + fileName.substring(lastIndexOfDot); maxProjection = "MAX(CAST(SUBSTRING(file_name, LOCATE('" + numDelim + "', file_name) + 1, LOCATE('" + extensionDelim + "', file_name) - LOCATE('" + numDelim + "', file_name) - 1) AS SIGNED)) AS num"; } else { fileNameSearchCriteria = fileName + numDelim + "%"; maxProjection = "MAX(CAST(SUBSTRING(file_name, LOCATE('" + numDelim + "', file_name) + 1) AS SIGNED)) AS num"; } return (Number) (getCriteria().add(eq("userId", userId)).add(like("xmlSchema", xmlSchema)) .add(like("file.name", fileNameSearchCriteria)) .setProjection(Projections.sqlProjection(maxProjection, new String[] {"num"}, new Type[] {new IntegerType()})) .uniqueResult()); }
public SqliteDialect() { super(); registerColumnType(Types.BIT, "integer"); registerColumnType(Types.TINYINT, "tinyint"); registerColumnType(Types.SMALLINT, "smallint"); registerColumnType(Types.INTEGER, "integer"); registerColumnType(Types.BIGINT, "bigint"); registerColumnType(Types.FLOAT, "float"); registerColumnType(Types.REAL, "real"); registerColumnType(Types.DOUBLE, "double"); registerColumnType(Types.NUMERIC, "numeric"); registerColumnType(Types.DECIMAL, "decimal"); registerColumnType(Types.CHAR, "char"); registerColumnType(Types.VARCHAR, "varchar"); registerColumnType(Types.LONGVARCHAR, "longvarchar"); registerColumnType(Types.DATE, "date"); registerColumnType(Types.TIME, "time"); registerColumnType(Types.TIMESTAMP, "timestamp"); registerColumnType(Types.BINARY, "blob"); registerColumnType(Types.VARBINARY, "blob"); registerColumnType(Types.LONGVARBINARY, "blob"); registerColumnType(Types.BLOB, "blob"); registerColumnType(Types.CLOB, "clob"); registerColumnType(Types.BOOLEAN, "integer"); registerFunction("concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "")); registerFunction("mod", new SQLFunctionTemplate(IntegerType.INSTANCE, "?1 % ?2")); registerFunction("substr", new StandardSQLFunction("substr", StringType.INSTANCE)); registerFunction("substring", new StandardSQLFunction("substr", StringType.INSTANCE)); }
@Override @SuppressWarnings("unchecked") /** Returns < [surveySession, numUsers] ... [surveySession, numUsers]> */ public List<Object[]> getStatisticsBySession(final Long contentId) { SQLQuery query = getSession().createSQLQuery(GET_STATISTICS); query.addEntity(SurveySession.class).addScalar("numUsers", IntegerType.INSTANCE).setLong("contentId", contentId); return query.list(); }
@Override public List<MonitoringSummarySessionDTO> statistics(Long toolContentUid) { SQLQuery query = getSession().createSQLQuery(DacoSessionDAOHibernate.CALC_SESSION_STATS); query.addScalar("sessionId", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE) .addScalar("numberLearners", IntegerType.INSTANCE).addScalar("totalRecordCount", IntegerType.INSTANCE) .setLong("contentUid", toolContentUid) .setResultTransformer(Transformers.aliasToBean(MonitoringSessionStatsDTO.class)); return query.list(); }
@Override @SuppressWarnings("unchecked") /** * Gets the basic details about an attempt for a nomination. questionUid must not be null, sessionUid may be NULL. * This is * unusual for these methods - usually sessionId may not be null. In this case if sessionUid is null then you get * the values for the whole class, not just the group. * * Will return List<[login (String), fullname(String), attemptTime(Timestamp]> */ public List<Object[]> getUserAttemptsForTablesorter(Long sessionUid, Long questionUid, int page, int size, int sorting, String searchString, IUserManagementService userManagementService) { String sortingOrder; switch (sorting) { case VoteAppConstants.SORT_BY_NAME_ASC: sortingOrder = "user.fullname ASC"; break; case VoteAppConstants.SORT_BY_NAME_DESC: sortingOrder = "user.fullname DESC"; break; case VoteAppConstants.SORT_BY_DATE_ASC: sortingOrder = "attempt.attempt_time ASC"; break; case VoteAppConstants.SORT_BY_DATE_DESC: sortingOrder = "attempt.attempt_time DESC"; break; default: sortingOrder = "user.uid"; } String[] portraitStrings = userManagementService.getPortraitSQL("user.user_id"); // Basic select for the user records StringBuilder queryText = new StringBuilder(FIND_USER_ANSWERS_BY_QUESTION_UID_SELECT) .append(portraitStrings[0]) .append(FIND_USER_ANSWERS_BY_QUESTION_UID_FROM) .append(portraitStrings[1]); if (sessionUid != null) { queryText.append(FIND_USER_ANSWERS_BY_QUESTION_UID_SESSION_ADDITION); } // If filtering by name add a name based where clause buildNameSearch(searchString, queryText, true); // Now specify the sort based on the switch statement above. queryText.append(" ORDER BY " + sortingOrder); SQLQuery query = getSession().createSQLQuery(queryText.toString()); query.addScalar("user_id", IntegerType.INSTANCE).addScalar("username", StringType.INSTANCE) .addScalar("fullname", StringType.INSTANCE) .addScalar("attemptTime", TimestampType.INSTANCE) .addScalar("portraitId", IntegerType.INSTANCE) .setLong("questionUid", questionUid.longValue()) .setFirstResult(page * size).setMaxResults(size); if (sessionUid != null) { query.setLong("sessionUid", sessionUid.longValue()); } return query.list(); }
@Override @SuppressWarnings("unchecked") public List<StatisticDTO> getStatisticsBySession(final Long contentId) { SQLQuery query = getSession().createSQLQuery(GET_STATISTICS); query.addScalar("sessionId", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE) .addScalar("numLearners", IntegerType.INSTANCE).addScalar("numLearnersFinished", IntegerType.INSTANCE) .setLong("contentId", contentId).setResultTransformer(Transformers.aliasToBean(StatisticDTO.class)); return query.list(); }
@Override @SuppressWarnings("unchecked") public List<StatisticDTO> getStatisticsBySession(final Long contentId) { SQLQuery query = getSession().createSQLQuery(GET_STATISTICS); query.addScalar("sessionId", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE) .addScalar("totalUploadedFiles", IntegerType.INSTANCE).addScalar("markedCount", IntegerType.INSTANCE) .setLong("contentId", contentId).setResultTransformer(Transformers.aliasToBean(StatisticDTO.class)); List<StatisticDTO> list = query.list(); for (StatisticDTO dto : list) { dto.setNotMarkedCount(dto.getTotalUploadedFiles() - dto.getMarkedCount()); } return list; }
@Override @SuppressWarnings("unchecked") public List<StatisticDTO> getLeaderStatisticsBySession(final Long contentId) { SQLQuery query = getSession().createSQLQuery(GET_LEADER_STATISTICS); query.addScalar("sessionId", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE) .addScalar("totalUploadedFiles", IntegerType.INSTANCE).addScalar("markedCount", IntegerType.INSTANCE) .setLong("contentId", contentId).setResultTransformer(Transformers.aliasToBean(StatisticDTO.class)); List<StatisticDTO> list = query.list(); for (StatisticDTO dto : list) { dto.setNotMarkedCount(dto.getTotalUploadedFiles() - dto.getMarkedCount()); } return list; }
@Override @SuppressWarnings("unchecked") public SortedSet<Comment> getThreadByThreadId(Long threadCommentId, Integer sortBy, Integer userId) { SQLQuery query = getSession().createSQLQuery(SQL_QUERY_GET_COMPLETE_THREAD); query.addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("userId", userId != null ? userId : 0) .setLong("threadId", threadCommentId); List<Object[]> results = query.list(); return upgradeComments(results, sortBy); }
@SuppressWarnings({ "unchecked" }) private SortedSet<Comment> getNextThreadByThreadIdLikes(final Long rootTopicId, final Long previousThreadMessageId, Integer numberOfThreads, Integer sortBy, String extraSortParam, Integer userId) { // the search to get to the top level is quite heavy and involves grouping the likes, so get all the data // for the top level then get the child replies. List<Object[]> topThreadObjects = null; if (previousThreadMessageId == null || previousThreadMessageId == 0L) { topThreadObjects = getSession().createSQLQuery(SQL_QUERY_FIND_FIRST_THREAD_TOP_BY_LIKES) .addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("rootUid", rootTopicId) .setLong("userId", userId != null ? userId : 0).setMaxResults(numberOfThreads).list(); } else { // get more entries with the same number of likes or less likes topThreadObjects = getSession().createSQLQuery(SQL_QUERY_FIND_NEXT_THREAD_TOP_BY_LIKE) .addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("rootUid", rootTopicId) .setLong("lastUid", previousThreadMessageId).setString("like", extraSortParam) .setLong("userId", userId != null ? userId : 0).setMaxResults(numberOfThreads).list(); } if (topThreadObjects != null && topThreadObjects.size() > 0) { // build the list of uids List<Number> threadUidList = new ArrayList<Number>(); for (Object[] rawObject : topThreadObjects) { Comment comment = (Comment) rawObject[0]; threadUidList.add(comment.getUid()); } SQLQuery query = getSession().createSQLQuery(SQL_QUERY_FIND_NEXT_THREAD_MESSAGES_REPLIES_ONLY); query.addEntity("comment", Comment.class).addScalar("likes_total", IntegerType.INSTANCE) .addScalar("user_vote", IntegerType.INSTANCE).setLong("userId", userId != null ? userId : 0) .setParameterList("threadIds", threadUidList); List<Object[]> results = query.list(); topThreadObjects.addAll(results); return upgradeComments(topThreadObjects, sortBy); } return new TreeSet<Comment>(); }
public static void addBitwiseOperationsToDialect() { SessionFactoryImplementor hibSessionFactory = (SessionFactoryImplementor)new _RootDAO().getSession().getSessionFactory(); Dialect dialect = hibSessionFactory.getDialect(); if (!dialect.getFunctions().containsKey("bit_and")) { if (isOracle()) dialect.getFunctions().put("bit_and", new StandardSQLFunction("bitand", IntegerType.INSTANCE)); else dialect.getFunctions().put("bit_and", new SQLFunctionTemplate(IntegerType.INSTANCE, "?1 & ?2")); } }
private int quickCheck(Session session) { Query q = session.createSQLQuery( "select count(m_org.oid) as problems from m_org left join m_org_closure cl " + "on cl.descendant_oid = m_org.oid and cl.ancestor_oid = m_org.oid " + "where cl.descendant_oid is null").addScalar("problems", IntegerType.INSTANCE); List problemsList = q.list(); if (problemsList == null || problemsList.size() != 1) { throw new IllegalStateException("Unexpected return value from the closure check query: " + problemsList + " (a 1-item list of Integer expected)"); } return (int) problemsList.get(0); }
private void dumpOrgClosureTypeTable(Session session, String tableName) { Query q = session.createSQLQuery("select descendant_oid, ancestor_oid, val from " + tableName) .addScalar("descendant_oid", StringType.INSTANCE) .addScalar("ancestor_oid", StringType.INSTANCE) .addScalar("val", IntegerType.INSTANCE); List<Object[]> list = q.list(); LOGGER.trace("{} ({} rows):", tableName, list.size()); for (Object[] row : list) { LOGGER.trace(" - [d={}, a={}, val={}]", row); } }
private void fetchByPageId(int pageID) throws WikiApiException { Session session = this.wiki.__getHibernateSession(); session.beginTransaction(); hibernatePage = (de.tudarmstadt.ukp.wikipedia.api.hibernate.Page) session .createQuery("from Page where pageId = :id").setParameter("id", pageID, IntegerType.INSTANCE).uniqueResult(); session.getTransaction().commit(); if (hibernatePage == null) { throw new WikiPageNotFoundException("No page with page id " + pageID + " was found."); } }
/** * Gets the title for a given pageId. * * @param pageId The id of the page. * @return The title for the given pageId. * @throws WikiApiException */ public Title getTitle(int pageId) throws WikiApiException { Session session = this.__getHibernateSession(); session.beginTransaction(); Object returnValue = session.createNativeQuery( "select p.name from PageMapLine as p where p.id = :pId").setParameter("pId", pageId, IntegerType.INSTANCE).uniqueResult(); session.getTransaction().commit(); String title = (String)returnValue; if(title==null){ throw new WikiPageNotFoundException(); } return new Title(title); }
/** * Get the hibernate ID to a given pageID of a page. * We need different methods for pages and categories here, as a page and a category can have the same ID. * * @param pageID A pageID that should be mapped to the corresponding hibernate ID. * @return The hibernateID of the page with pageID or -1, if the pageID is not valid */ protected long __getPageHibernateId(int pageID) { long hibernateID = -1; // first look in the id mapping cache if (idMapPages.containsKey(pageID)) { return idMapPages.get(pageID); } // The id was not found in the id mapping cache. // It may not be in the cahe or may not exist at all. Session session = this.__getHibernateSession(); session.beginTransaction(); Object retObjectPage = session.createQuery( "select page.id from Page as page where page.pageId = :pageId") .setParameter("pageId", pageID, IntegerType.INSTANCE) .uniqueResult(); session.getTransaction().commit(); if (retObjectPage != null) { hibernateID = (Long) retObjectPage; // add it to the cache idMapPages.put(pageID, hibernateID); return hibernateID; } return hibernateID; }
@Override @SuppressWarnings("rawtypes") public Object readGenericEntity(Class<?> clazz, Object id) { Map<String, Object> md = daoHelper.getIdMetadata(clazz, (HibernateEntityManager) em); AbstractSingleColumnStandardBasicType type = (AbstractSingleColumnStandardBasicType) md.get("type"); if (type instanceof LongType) { id = Long.parseLong(String.valueOf(id)); } else if (type instanceof IntegerType) { id = Integer.parseInt(String.valueOf(id)); } return em.find(clazz, id); }
public SQLiteDialect() { registerColumnType(Types.BIT, "integer"); registerColumnType(Types.TINYINT, "tinyint"); registerColumnType(Types.SMALLINT, "smallint"); registerColumnType(Types.INTEGER, "integer"); registerColumnType(Types.BIGINT, "bigint"); registerColumnType(Types.FLOAT, "float"); registerColumnType(Types.REAL, "real"); registerColumnType(Types.DOUBLE, "double"); registerColumnType(Types.NUMERIC, "numeric"); registerColumnType(Types.DECIMAL, "decimal"); registerColumnType(Types.CHAR, "char"); registerColumnType(Types.VARCHAR, "varchar"); registerColumnType(Types.LONGVARCHAR, "longvarchar"); registerColumnType(Types.DATE, "date"); registerColumnType(Types.TIME, "time"); registerColumnType(Types.TIMESTAMP, "timestamp"); registerColumnType(Types.BINARY, "blob"); registerColumnType(Types.VARBINARY, "blob"); registerColumnType(Types.LONGVARBINARY, "blob"); // registerColumnType(Types.NULL, "null"); registerColumnType(Types.BLOB, "blob"); registerColumnType(Types.CLOB, "clob"); registerColumnType(Types.BOOLEAN, "integer"); registerFunction("concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "")); registerFunction("mod", new SQLFunctionTemplate(IntegerType.INSTANCE, "?1 % ?2")); registerFunction("substr", new StandardSQLFunction("substr", StringType.INSTANCE)); registerFunction("substring", new StandardSQLFunction("substr", StringType.INSTANCE)); }
@Override public <T> T readGenericEntity(Class<T> clazz, Object id) { clazz = (Class<T>) DynamicDaoHelperImpl.getNonProxyImplementationClassIfNecessary(clazz); Map<String, Object> md = daoHelper.getIdMetadata(clazz, (HibernateEntityManager) em); AbstractSingleColumnStandardBasicType type = (AbstractSingleColumnStandardBasicType) md.get("type"); if (type instanceof LongType) { id = Long.parseLong(String.valueOf(id)); } else if (type instanceof IntegerType) { id = Integer.parseInt(String.valueOf(id)); } return em.find(clazz, id); }
private int quickCheck(Session session) { NativeQuery q = session.createNativeQuery( "select count(m_org.oid) as problems from m_org left join m_org_closure cl " + "on cl.descendant_oid = m_org.oid and cl.ancestor_oid = m_org.oid " + "where cl.descendant_oid is null").addScalar("problems", IntegerType.INSTANCE); List problemsList = q.list(); if (problemsList == null || problemsList.size() != 1) { throw new IllegalStateException("Unexpected return value from the closure check query: " + problemsList + " (a 1-item list of Integer expected)"); } return (int) problemsList.get(0); }
private void dumpOrgClosureTypeTable(Session session, String tableName) { NativeQuery q = session.createNativeQuery("select descendant_oid, ancestor_oid, val from " + tableName) .addScalar("descendant_oid", StringType.INSTANCE) .addScalar("ancestor_oid", StringType.INSTANCE) .addScalar("val", IntegerType.INSTANCE); List<Object[]> list = q.list(); LOGGER.trace("{} ({} rows):", tableName, list.size()); for (Object[] row : list) { LOGGER.trace(" - [d={}, a={}, val={}]", row); } }
private Integer numberOfSnapshots(Long sid) { Session session = HibernateFactory.getSession(); return (Integer) session.createSQLQuery("Select count(*) as cnt " + " from rhnSnapshot " + " where server_id = " + sid) .addScalar("cnt", new IntegerType()) .uniqueResult(); }