List of usage examples for org.hibernate Query setMaxResults
@Override
Query<R> setMaxResults(int maxResult);
From source file:com.corendal.netapps.wiki.writedatabeans.AbstractArticleVersion.java
License:Open Source License
@Override public void load() { /*//from w w w . jav a 2s. com * set the record as "not found" */ this.setIsFound(false); /* * initialize the prepared statement and the result set */ PreparedStatement prepStmt = null; ResultSet rs = null; /* * get the JDBC data session */ HibernateDataSession ds = DataSessionSetGlobal.get() .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED); /* * get the primary key of the article version */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.ARTICLE_VERSIONS); PrimaryKey recordPk = this.getPrimaryKey(); /* * retrieve the article version information from the database */ String selectStatement = "select content_version.version_num, " + "content_version.version_info_id, content_version.request_id, " + "content.enabled_flag, content_version.current_flag, content_version.content_id, " + "content_version.body, content.content_rule_typ_id, content_version.cmnt " + "from " + ds.getTableNameWithDefaultSchema("content_version") + ", " + ds.getTableNameWithDefaultSchema("content") + " " + "where content_version.id = ? " + "and content.content_typ_id = ? " + "and content.id = content_version.content_id "; // FIXME: hibernate select query try { /* * create the prepared statement */ prepStmt = ds.getReadConnection().prepareStatement(selectStatement); /* * associate the id and the article version type */ prepStmt.setString(1, recordPk.toString()); prepStmt.setString(2, ContentTypesDictionary.ARTICLE); /* * execute the query */ rs = prepStmt.executeQuery(); /* * loop the results */ while (rs.next()) { this.setIsFound(true); this.versionNum = rs.getInt(1); this.versionInfoId = rs.getString(2); this.requestId = rs.getString(3); this.enabledFlag = rs.getString(4); this.currentFlag = rs.getString(5); this.contentId = rs.getString(6); this.rawBodyHTML = ds.getStringFromCharacterStream(rs, 7); this.contentRuleTypeId = rs.getString(8); this.comment = ds.getStringFromCharacterStream(rs, 9); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } finally { /* * close the recordset and the prepared statement */ CloseUtil.closeResultSet(rs); CloseUtil.closePreparedStatement(prepStmt); } /* * retrieve the author information from the database */ if (this.getIsFound()) { PrimaryKey rolePk = PrimaryKeyUtil.getAlphanumericSingleKey(RolesDictionary.AUTHOR); this.authorId = AccountRoleXrefFactory.getSingleAccountId(this, ds, entityPk, rolePk, recordPk); } /* * retrieve the body text information from the database */ if (this.getIsFound()) { try { /* * get the query */ Query query = ds.getReadNamedQuery(LOAD); /* * associate the query parameters */ query.setParameter("contentVersionId", recordPk.toString()); /* * only get one content body */ query.setMaxResults(1); /* * get content body mapping */ ContentBodyMapping contentBodyMapping = (ContentBodyMapping) query.uniqueResult(); this.bodyHTML = null; this.bodyText = null; /* * store values from mapping */ if (contentBodyMapping != null) { this.bodyHTML = contentBodyMapping.getBodyHtml(); this.bodyText = contentBodyMapping.getBodyText(); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } } }
From source file:com.corendal.netapps.wiki.writedatabeans.AbstractImage.java
License:Open Source License
@Override public void load() { /*//from w w w . j av a 2 s .c o m * set the record as "not found" */ this.setIsFound(false); /* * initialize the prepared statement and the result set */ PreparedStatement prepStmt = null; ResultSet rs = null; /* * get the JDBC data session */ HibernateDataSession ds = DataSessionSetGlobal.get() .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED); /* * get the primary key of the image */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.IMAGES); PrimaryKey recordPk = this.getPrimaryKey(); /* * retrieve the image information from the database */ String selectStatement = "select content_version.version_num, " + "content_version.version_info_id, content_version.request_id, " + "content_version.friendly_address, " + "content.content_class_typ_id, content_version.id, " + "content.content_rule_typ_id, content_version.cmnt, content.enabled_flag " + "from " + ds.getTableNameWithDefaultSchema("content_version") + ", " + ds.getTableNameWithDefaultSchema("content") + " " + "where content_version.content_id = ? " + "and content.content_typ_id = ? " + "and content_version.current_flag = ? " + "and content.id = content_version.content_id "; // FIXME: hibernate select query try { /* * create the prepared statement */ prepStmt = ds.getReadConnection().prepareStatement(selectStatement); /* * associate the id and the image type */ prepStmt.setString(1, recordPk.toString()); prepStmt.setString(2, ContentTypesDictionary.IMAGE); prepStmt.setString(3, "Y"); /* * execute the query */ rs = prepStmt.executeQuery(); /* * loop the results */ while (rs.next()) { this.setIsFound(true); this.versionNum = rs.getInt(1); this.versionInfoId = rs.getString(2); this.requestId = rs.getString(3); this.friendlyAddress = rs.getString(4); this.contentClassTypeId = rs.getString(5); this.versionId = rs.getString(6); this.contentRuleTypeId = rs.getString(7); this.comment = ds.getStringFromCharacterStream(rs, 8); this.enabledFlag = rs.getString(9); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } finally { /* * close the recordset and the prepared statement */ CloseUtil.closeResultSet(rs); CloseUtil.closePreparedStatement(prepStmt); } /* * retrieve the parent information from the database */ if (this.getIsFound()) { /* * retrieve the parent information from the database */ try { /* * get the query */ Query query = ds.getReadNamedQuery(LOAD); /* * associate the query parameters */ query.setParameter("childContentId", recordPk.toString()); query.setParameter("mainFlag", "Y"); /* * only get one content map */ query.setMaxResults(1); /* * get content map mapping */ ContentMapMapping contentMapMapping = (ContentMapMapping) query.uniqueResult(); /* * store values from mapping */ if (contentMapMapping != null) { this.mainParentId = contentMapMapping.getParentContentId(); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } } /* * retrieve the author information from the database */ if (this.getIsFound()) { selectStatement = "select account_role_xref.account_id " + "from " + ds.getTableNameWithDefaultSchema("account_role_xref") + ", " + ds.getTableNameWithDefaultSchema("content_version") + " " + "where content_version.version_num= ? " + "and content_version.content_id = ? " + "and account_role_xref.role_id = ? " + "and account_role_xref.entity_id = ? " + "and content_version.id=account_role_xref.record_id"; // FIXME: hibernate select query try { /* * create the prepared statement */ prepStmt = ds.getReadConnection().prepareStatement(selectStatement); /* * associate the id, the version number and the editor role */ prepStmt.setInt(1, this.versionNum); prepStmt.setString(2, recordPk.toString()); prepStmt.setString(3, RolesDictionary.AUTHOR); prepStmt.setString(4, EntitiesDictionary.IMAGE_VERSIONS); /* * execute the query */ rs = prepStmt.executeQuery(); /* * loop the results */ this.authorId = null; while (rs.next()) { this.authorId = rs.getString(1); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } finally { /* * close the recordset and the prepared statement */ CloseUtil.closeResultSet(rs); CloseUtil.closePreparedStatement(prepStmt); } } /* * retrieve the file information from the database */ if (this.getIsFound()) { selectStatement = "select file_obj_role_xref.file_obj_id " + "from " + ds.getTableNameWithDefaultSchema("file_obj_role_xref") + ", content_version " + "where content_version.version_num= ? " + "and content_version.content_id = ? " + "and file_obj_role_xref.role_id = ? " + "and file_obj_role_xref.entity_id = ? " + "and content_version.id=file_obj_role_xref.record_id"; // FIXME: hibernate select query try { /* * create the prepared statement */ prepStmt = ds.getReadConnection().prepareStatement(selectStatement); /* * associate the id, the version number and the editor role */ prepStmt.setInt(1, this.versionNum); prepStmt.setString(2, recordPk.toString()); prepStmt.setString(3, RolesDictionary.ATTACHMENT); prepStmt.setString(4, EntitiesDictionary.IMAGE_VERSIONS); /* * execute the query */ rs = prepStmt.executeQuery(); /* * loop the results */ this.fileId = null; while (rs.next()) { this.fileId = rs.getString(1); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } finally { /* * close the recordset and the prepared statement */ CloseUtil.closeResultSet(rs); CloseUtil.closePreparedStatement(prepStmt); } } /* * load this write data bean */ if (this.getIsFound()) { super.load(entityPk, recordPk); } }
From source file:com.corendal.netapps.wiki.writedatabeans.AbstractImage.java
License:Open Source License
public PrimaryKey getFirstRequestPrimaryKey() { /*//from w ww . j av a 2 s . co m * initialize the request id */ String firstRequestId = null; /* * get the JDBC data session */ HibernateDataSession ds = DataSessionSetGlobal.get() .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED); /* * get the primary key of the image */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.IMAGES); PrimaryKey recordPk = this.getPrimaryKey(); try { /* * get the query */ Query query = ds.getReadNamedQuery(GET_FIRST_REQUEST_PRIMARY_KEY); /* * associate the query parameters */ query.setParameter("contentId", recordPk.toString()); query.setParameter("versionNumber", 1); /* * only get one version */ query.setMaxResults(1); /* * get content version mapping */ ContentVersionMapping contentVersionMapping = (ContentVersionMapping) query.uniqueResult(); /* * store values from mapping */ if (contentVersionMapping != null) { firstRequestId = contentVersionMapping.getRequestId(); } } catch (Exception e) { /* * log the exception */ this.appendLoadTrace(e.getMessage()); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, recordPk); } /* * return */ return PrimaryKeyUtil.getAlphanumericSingleKeyOrNull(firstRequestId); }
From source file:com.corendal.netapps.wiki.writedatabeans.AbstractImage.java
License:Open Source License
/** * Returns a ranked list of all image primary keys that have been accessed. * //from ww w . j ava2 s .com * @param cnt * number of rows to return * * * @return a java.util.List object */ public static final List<PrimaryKey> findEnabledByRank(int cnt) { /* * initialize the result */ List<PrimaryKey> primaryKeys = new ArrayList<PrimaryKey>(); /* * initialize the prepared statement and the result set */ PreparedStatement prepStmt = null; ResultSet rs = null; /* * get the JDBC data session */ HibernateDataSession ds = DataSessionSetGlobal.get() .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED); /* * retrieve the content access period information from the database */ Date maxAccessDate = null; try { /* * get the query */ Query query = ds.getReadNamedQuery(FIND_ENABLED_BY_RANK_1); /* * only get one benefit */ query.setMaxResults(1); /* * get benefit mapping */ maxAccessDate = (Date) query.uniqueResult(); } catch (Exception e) { /* * log the exception */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.IMAGES); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, null); } /* * retrieve the content information from the database */ if (maxAccessDate != null) { String selectStatement = "select content_id, access_rank, access_num " + "from " + ds.getTableNameWithDefaultSchema("content_access_period") + ", " + ds.getTableNameWithDefaultSchema("content") + " " + "where content_access_period.content_id = content.id " + "and content.content_typ_id = ? " + "and content_access_period.access_date = ? " + "order by access_date desc, access_rank "; // FIXME: hibernate select query try { /* * create the prepared statement */ prepStmt = ds.getReadConnection().prepareStatement(selectStatement); /* * associate the id */ prepStmt.setString(1, ContentTypesDictionary.IMAGE); prepStmt.setDate(2, DateUtil.getDateToSQLDate(maxAccessDate)); /* * execute the query */ rs = prepStmt.executeQuery(); /* * loop the results */ int itemCount = 0; while ((rs.next()) && (itemCount < cnt)) { PrimaryKey pk = PrimaryKeyUtil.getAlphanumericSingleKey(rs.getString(1)); primaryKeys.add(pk); itemCount++; } } catch (Exception e) { /* * log the exception */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.IMAGES); LoggerUtil.logError(ABSTRACT_CLASS_NAME, e, entityPk, null); } finally { /* * close the recordset and the prepared statement */ CloseUtil.closeResultSet(rs); CloseUtil.closePreparedStatement(prepStmt); } } /* * return all image primary keys */ return primaryKeys; }
From source file:com.corendal.netapps.wiki.writedatafactories.ContentAccessDayFactory.java
License:Open Source License
/** * Fills the content_access_day with all missing data. * //from w w w . j a v a2s . c om * * */ public static void refresh() { /* * get the JDBC data session */ HibernateDataSession ds = DataSessionSetGlobal.get() .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED); /* * retrieve the content access day information from the database */ Date maxAccessDate = null; try { /* * get the query */ Query query = ds.getReadNamedQuery(REFRESH); /* * only get one benefit */ query.setMaxResults(1); /* * get benefit mapping */ maxAccessDate = (Date) query.uniqueResult(); } catch (Exception e) { /* * log the exception */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.CONTENT_ACCESS_DAYS); LoggerUtil.logError(STATIC_CLASS_NAME, e, entityPk, null); } /* * set the date to yesterday if no log found */ java.util.Date truncatedMaxAccessDate; java.util.Date today = DateUtil.getTruncated(new java.util.Date()); if (maxAccessDate == null) { truncatedMaxAccessDate = DateUtil.getRemovedDays(today, 15); } else { truncatedMaxAccessDate = DateUtil.getTruncated(maxAccessDate); } /* * refresh for each missing day */ long timeGapInDays = DateUtil.getTimeGapInDays(truncatedMaxAccessDate, today); for (int i = 1; i < timeGapInDays; i++) { java.util.Date currentDate = DateUtil.getAddedDays(truncatedMaxAccessDate, i); refresh(currentDate); } }
From source file:com.corendal.netapps.wiki.writedatafactories.ContentAccessPeriodFactory.java
License:Open Source License
/** * Fills the content_access_period with all missing data. * // ww w . j a v a 2s . c om * * */ public static void refresh() { /* * get the JDBC data session */ HibernateDataSession ds = DataSessionSetGlobal.get() .getSharedHibernateDataSession(DataSessionTypeConstants.WIKI_SHARED); /* * retrieve the content access period information from the database */ Date maxAccessDate = null; try { /* * get the query */ Query query = ds.getReadNamedQuery(REFRESH_1); /* * only get one benefit */ query.setMaxResults(1); /* * get benefit mapping */ maxAccessDate = (Date) query.uniqueResult(); } catch (Exception e) { /* * log the exception */ PrimaryKey entityPk = PrimaryKeyUtil .getAlphanumericSingleKey(EntitiesDictionary.CONTENT_ACCESS_PERIODS); LoggerUtil.logError(STATIC_CLASS_NAME, e, entityPk, null); } /* * set the date to 15 days ago if no log found */ java.util.Date truncatedMaxAccessDate; java.util.Date today = DateUtil.getTruncated(new java.util.Date()); if (maxAccessDate == null) { truncatedMaxAccessDate = DateUtil.getRemovedDays(today, 15); } else { truncatedMaxAccessDate = DateUtil.getTruncated(maxAccessDate); } /* * retrieve the content access day information from the database */ Date minAccessDate = null; try { /* * get the query */ Query query = ds.getReadNamedQuery(REFRESH_2); /* * only get one benefit */ query.setMaxResults(1); /* * get benefit mapping */ minAccessDate = (Date) query.uniqueResult(); } catch (Exception e) { /* * log the exception */ PrimaryKey entityPk = PrimaryKeyUtil.getAlphanumericSingleKey(EntitiesDictionary.CONTENT_ACCESS_DAYS); LoggerUtil.logError(STATIC_CLASS_NAME, e, entityPk, null); } /* * refresh for each missing period */ if (minAccessDate != null) { long timeGapInDays = DateUtil.getTimeGapInDays(truncatedMaxAccessDate, minAccessDate); for (int i = 1; i <= timeGapInDays; i++) { java.util.Date currentDate = DateUtil.getAddedDays(truncatedMaxAccessDate, i); refresh(currentDate); } } }
From source file:com.crossover.assignment.NativeApiIllustrationTest.java
License:Open Source License
public void testGetLatestOnlineTestForUser() { UserCredentials user = new UserCredentials(); String userId = "user1"; String password = "hash1"; user.setUserId(userId);/*from w w w.jav a 2 s. com*/ user.setPassword(password); Transaction transaction = null; try (Session session = sessionFactory.openSession()) { transaction = session.beginTransaction(); Query query = session.createQuery(Queries.QUERY_LATEST_TEST); query.setMaxResults(1); @SuppressWarnings("unchecked") List<UserTest> testList = query.setParameter("userId", user.getUserId()).list(); if (!testList.isEmpty()) { UserTest latestTest = testList.get(0); Test test = latestTest.getTest(); System.out.println("Test is " + latestTest.getTest()); System.out.println("User is " + latestTest.getUser()); OnlineTest onlineTest = new OnlineTest(test.getId(), test.getName(), test.getDescription()); System.out.println("OnlineTests retrieved is " + testList.size()); } transaction.commit(); } catch (Exception e) { e.printStackTrace(); if (transaction != null) { transaction.rollback(); } } }
From source file:com.cyclopsgroup.tornado.hibernate.HqlLargeList.java
License:CDDL license
/** * Overwrite or implement method iterate() * * @see com.cyclopsgroup.waterview.LargeList#iterate(int, int, com.cyclopsgroup.waterview.LargeList.Sorting[]) *///from w w w. jav a 2 s . co m public Iterator iterate(int startPosition, int maxRecords, Sorting[] sortings) throws Exception { if (StringUtils.isEmpty(hql)) { throw new IllegalStateException("query is still emtpy"); } Session s = hibernate.getSession(dataSource); StringBuffer sb = new StringBuffer(hql); boolean first = true; for (int i = 0; i < sortings.length; i++) { Sorting sorting = sortings[i]; if (first) { sb.append(" ORDER BY "); first = false; } else { sb.append(", "); } sb.append(sorting.getName()); if (sorting.isDescending()) { sb.append(" DESC"); } } Query q = s.createQuery(sb.toString()); HashSet parameterNames = new HashSet(); CollectionUtils.addAll(parameterNames, q.getNamedParameters()); for (Iterator i = parameters.values().iterator(); i.hasNext();) { Parameter p = (Parameter) i.next(); if (parameterNames.contains(p.getName())) { q.setParameter(p.getName(), p.getValue(), p.getType()); } } q.setFirstResult(startPosition); if (maxRecords > 0) { q.setMaxResults(maxRecords); } return q.iterate(); }
From source file:com.dell.asm.asmcore.asmmanager.db.DeviceConfigureDAO.java
License:Open Source License
/** * Retrieve DeviceConfigureEntity based on id. * /*from w ww . j ava 2 s . com*/ * @return the DeviceConfigureEntity. */ public DeviceConfigureEntity getDeviceConfigureEntityById(String id) throws AsmManagerDAOException { Session session = null; Transaction tx = null; DeviceConfigureEntity deviceConfigureEntity = null; try { session = _dao._database.getNewSession(); tx = session.beginTransaction(); // Create and execute command. String hql = "from DeviceConfigureEntity where id =:id"; Query query = session.createQuery(hql); query.setString("id", id); deviceConfigureEntity = (DeviceConfigureEntity) query.setMaxResults(1).uniqueResult(); // Commit transaction. tx.commit(); } catch (Exception e) { logger.warn("Caught exception during get deviceConfigureEntity for id: " + id + ", " + e); try { if (tx != null) { tx.rollback(); } } catch (Exception ex) { logger.warn("Unable to rollback transaction during get deviceConfigureEntity: " + ex); } throw new AsmManagerInternalErrorException("Retrieve deviceConfigureEntity by Id", "DeviceConfigureDAO", e); } finally { try { if (session != null) { session.close(); } } catch (Exception ex) { logger.warn("Unable to close session during get deviceConfigure: " + ex); } } return deviceConfigureEntity; }
From source file:com.dell.asm.asmcore.asmmanager.db.DeviceConfigureDAO.java
License:Open Source License
public boolean updateDeviceConfigureEntity(DeviceConfigureEntity deviceConfigureEntity, ConfigureStatus status) throws AsmManagerCheckedException { Session session = null;//from w ww . j av a 2s . com Transaction tx = null; boolean updatedFlag = false; try { session = _dao._database.getNewSession(); tx = session.beginTransaction(); String hql = "from DeviceConfigureEntity where id = :id"; Query query = session.createQuery(hql); query.setString("id", deviceConfigureEntity.getId()); DeviceConfigureEntity databaseDeviceConfigureEntity = (DeviceConfigureEntity) query.setMaxResults(1) .uniqueResult(); if (databaseDeviceConfigureEntity == null) { throw new AsmManagerCheckedException(AsmManagerCheckedException.REASON_CODE.RECORD_NOT_FOUND, AsmManagerMessages.notFound(deviceConfigureEntity.getId())); } databaseDeviceConfigureEntity.setStatus(status); databaseDeviceConfigureEntity.setUpdatedDate(new GregorianCalendar()); databaseDeviceConfigureEntity.setUpdatedBy(_dao.extractUserFromRequest()); session.saveOrUpdate(databaseDeviceConfigureEntity); // Commit transaction. tx.commit(); updatedFlag = true; } catch (Exception e) { logger.warn("Caught exception during update device configure entity : " + e); try { if (tx != null) { tx.rollback(); updatedFlag = false; } } catch (Exception ex) { logger.warn("Unable to rollback transaction during update device configure entity : " + ex); } if (e instanceof AsmManagerCheckedException) { throw e; } throw new AsmManagerInternalErrorException("Update device", "DeviceConfigureDAO", e); } finally { try { if (session != null) { session.close(); } } catch (Exception ex) { logger.warn("Unable to close session during update device configure entity : " + ex); } } return updatedFlag; }