Java Code Examples for org.hibernate.query.Query

The following examples show how to use org.hibernate.query.Query. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Insights   Source File: ToolsLayoutDAL.java    License: Apache License 2.0 6 votes vote down vote up
public ToolsLayout getToolLayout(String toolName, String toolCategory) {
	Query<ToolsLayout> createQuery = getSession().createQuery(
			"FROM ToolsLayout TL WHERE TL.toolName = :toolName AND TL.toolCategory = :toolCategory",
			ToolsLayout.class);
	createQuery.setParameter("toolName", toolName);
	createQuery.setParameter("toolCategory", toolCategory);
	ToolsLayout toolLayout = null;
	try{
		toolLayout = createQuery.getSingleResult();
	}catch(Exception e){
		throw new RuntimeException("Exception while retrieving data"+e);
	}
	terminateSession();
	terminateSessionFactory();
	return toolLayout;
}
 
Example 2
Source Project: modeldb   Source File: DatasetBlobFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static S3DatasetBlob getS3Blob(Session session, String blobHash) throws ModelDBException {
  String s3ComponentQueryHQL =
      "From "
          + S3DatasetComponentBlobEntity.class.getSimpleName()
          + " s3 WHERE s3.id.s3_dataset_blob_id = :blobShas";

  Query<S3DatasetComponentBlobEntity> s3ComponentQuery = session.createQuery(s3ComponentQueryHQL);
  s3ComponentQuery.setParameter("blobShas", blobHash);
  List<S3DatasetComponentBlobEntity> datasetComponentBlobEntities = s3ComponentQuery.list();

  if (datasetComponentBlobEntities != null && datasetComponentBlobEntities.size() > 0) {
    List<S3DatasetComponentBlob> componentBlobs =
        datasetComponentBlobEntities.stream()
            .map(S3DatasetComponentBlobEntity::toProto)
            .collect(Collectors.toList());
    return S3DatasetBlob.newBuilder().addAllComponents(componentBlobs).build();
  } else {
    throw new ModelDBException("S3 dataset Blob not found", Status.Code.NOT_FOUND);
  }
}
 
Example 3
Source Project: dkpro-jwpl   Source File: Wikipedia.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return an iterable containing all archived discussion pages for
 * the given article page. The most recent discussion page is not included.
 * The most recent discussion page can be obtained with {@link #getDiscussionPage(Page)}.
 * <br>
 * The provided page Object must not be a discussion page itself! If it is
 * a discussion page, is returned unchanged.
 *
 * @param articlePage the article page for which a discussion archives should be retrieved
 * @return An iterable with the discussion archive page objects for the given article page object
 * @throws WikiApiException If no page or redirect with this title exists or title could not be properly parsed.
 */
public Iterable<Page> getDiscussionArchives(Page articlePage) throws WikiApiException{
    String articleTitle = articlePage.getTitle().getWikiStyleTitle();
	if(!articleTitle.startsWith(WikiConstants.DISCUSSION_PREFIX)){
		articleTitle=WikiConstants.DISCUSSION_PREFIX+articleTitle;
	}

	Session session = this.__getHibernateSession();
    session.beginTransaction();

    List<Page> discussionArchives = new LinkedList<Page>();

    Query query = session.createQuery("SELECT pageID FROM PageMapLine where name like :name");
    query.setParameter("name", articleTitle+"/%", StringType.INSTANCE);
    Iterator results = query.list().iterator();

    session.getTransaction().commit();

    while (results.hasNext()) {
        int pageID = (Integer) results.next();
        discussionArchives.add(getPage(pageID));
    }

    return discussionArchives;

}
 
Example 4
Source Project: tutorials   Source File: ApplicationView.java    License: MIT License 6 votes vote down vote up
public String[] greaterThanCriteria() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Item> cr = cb.createQuery(Item.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(root)
        .where(cb.gt(root.get("itemPrice"), 1000));
    // cr.add(Restrictions.gt("itemPrice", 1000));
    Query<Item> query = session.createQuery(cr);
    final List<Item> greaterThanItemsList = query.getResultList();
    final String greaterThanItems[] = new String[greaterThanItemsList.size()];
    for (int i = 0; i < greaterThanItemsList.size(); i++) {
        greaterThanItems[i] = greaterThanItemsList.get(i)
            .getItemName();
    }
    session.close();
    return greaterThanItems;
}
 
Example 5
Source Project: uyuni   Source File: HibernateFactory.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Finds a single instance of a persistent object given a named query.
 * @param qryName The name of the query used to find the persistent object.
 * It should be formulated to ensure a single object is returned or an error
 * will occur.
 * @param qryParams Map of named bind parameters whose keys are Strings. The
 * map can also be null.
 * @param cacheable if we should cache the results of this object
 * @return Object found by named query or null if nothing found.
 */
protected Object lookupObjectByNamedQuery(String qryName, Map qryParams,
        boolean cacheable) {
    Object retval = null;
    Session session = null;

    try {
        session = HibernateFactory.getSession();

        Query query = session.getNamedQuery(qryName)
                .setCacheable(cacheable);
        bindParameters(query, qryParams);
        retval = query.uniqueResult();
    }
    catch (MappingException me) {
        throw new HibernateRuntimeException("Mapping not found for " + qryName, me);
    }
    catch (HibernateException he) {
        throw new HibernateRuntimeException("Executing query " + qryName +
                " with params " + qryParams + " failed", he);
    }

    return retval;
}
 
Example 6
@Override
public void setAllRoomsAtDirty(String dirty) {

    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<?> query = session.createQuery("UPDATE Room SET cleaningStatus=:dirty");
        query.setParameter("dirty", dirty);
        query.executeUpdate();
        
        logging.setMessage("RoomDaoImpl -> all rooms status updated to dirty successfully.");
    } catch (HibernateException e) {
        session.getTransaction().rollback();
        logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
    }
    session.close();
}
 
Example 7
@Override
public String getTotalCashLiraPostingsForOneDay(String today) {
    String totalCash = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<String> query = session.createQuery("select sum(price) from Posting where currency = 'TURKISH LIRA' and dateTime >= :today", String.class);
        query.setParameter("today", today);
        totalCash = query.getSingleResult();

        logging.setMessage("PostingDaoImpl -> fetching total cash lira posting for one day...");

    } catch (NoResultException e) {
        logging.setMessage("PostingDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return totalCash;
}
 
Example 8
Source Project: modeldb   Source File: RepositoryDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void saveBranch(
    Session session, String commitSHA, String branch, RepositoryEntity repository)
    throws ModelDBException {
  boolean exists =
      VersioningUtils.commitRepositoryMappingExists(session, commitSHA, repository.getId());
  if (!exists) {
    throw new ModelDBException(
        "Commit_hash and repository_id mapping not found for repository "
            + repository.getId()
            + " and commit "
            + commitSHA,
        Code.NOT_FOUND);
  }

  Query query = session.createQuery(CHECK_BRANCH_IN_REPOSITORY_HQL);
  query.setParameter("repositoryId", repository.getId());
  query.setParameter("branch", branch);
  BranchEntity branchEntity = (BranchEntity) query.uniqueResult();
  if (branchEntity != null) {
    if (branchEntity.getCommit_hash().equals(commitSHA)) return;
    session.delete(branchEntity);
  }

  branchEntity = new BranchEntity(repository.getId(), commitSHA, branch);
  session.save(branchEntity);
}
 
Example 9
@Override
public List<Reservation> getReservsAsWaitlist(String reservDate) {
    List<Reservation> reservationsList = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Reservation> query = session.createQuery("from Reservation "
                + "where bookStatus = 'WAITLIST' and checkinDate=:today", Reservation.class);
        query.setParameter("today", reservDate);
        reservationsList = query.getResultList();

        logging.setMessage("ReservationDaoImpl -> fetching all waiting reservations...");

    } catch (NoResultException e) {
        logging.setMessage("ReservationDaoImpl Error -> " + e.getLocalizedMessage());
    } finally {
        session.close();
    }
    return reservationsList;
}
 
Example 10
Source Project: lams   Source File: LessonDAO.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
   public Integer getCountLearnersByLesson(long lessonId, String searchPhrase) {
StringBuilder queryTextBuilder = new StringBuilder("SELECT COUNT(*) ")
	.append(LessonDAO.LOAD_LEARNERS_BY_LESSON);
if (!StringUtils.isBlank(searchPhrase)) {
    String[] tokens = searchPhrase.trim().split("\\s+");
    for (String token : tokens) {
	token = StringEscapeUtils.escapeSql(token).replace("\\", "\\\\");
	queryTextBuilder.append(" AND (users.firstName LIKE '%").append(token)
		.append("%' OR users.lastName LIKE '%").append(token).append("%' OR users.login LIKE '%")
		.append(token).append("%')");
    }
}

Query query = getSession().createQuery(queryTextBuilder.toString()).setLong("lessonId", lessonId);
Object value = query.uniqueResult();
return ((Number) value).intValue();
   }
 
Example 11
@Override
public Reservation findReservationByRefNo(String refNo) {
    Reservation reservationByRef = null;
    try {
        session = dataSourceFactory.getSessionFactory().openSession();
        beginTransactionIfAllowed(session);
        Query<Reservation> query = session.createQuery("from Reservation where referanceNo=:refNo", Reservation.class);
        query.setParameter("refNo", refNo);
        query.setMaxResults(1);
        reservationByRef = query.getSingleResult();

        logging.setMessage("ReservationDaoImpl -> fetching reservation by referance number...");

    } catch (NoResultException e) {
        final InformationFrame frame = new InformationFrame();
        frame.setMessage("There is no reservation with this referance number!");
        frame.setVisible(true);
    } finally {
        session.close();
    }
    return reservationByRef;

}
 
Example 12
protected <E> E getSingleResult(CriteriaQuery<E> criteriaQuery) {
  Query<E> query = getHibernateSession().createQuery(criteriaQuery);
  try {
    return query.getSingleResult();
  } catch (NoResultException noResultException) {
    return null;
  }
}
 
Example 13
Source Project: Insights   Source File: SettingsConfigurationDAL.java    License: Apache License 2.0 5 votes vote down vote up
public SettingsConfiguration loadSettingsConfiguration(String settingsType) {
	Query<SettingsConfiguration> loadQuery = getSession().createQuery("FROM SettingsConfiguration SC WHERE SC.settingsType = :settingsType", SettingsConfiguration.class);
	loadQuery.setParameter("settingsType", settingsType);
	List<SettingsConfiguration> results = loadQuery.getResultList();
	SettingsConfiguration settingsConfiguration = null;
	if (results != null && !results.isEmpty()) {
		settingsConfiguration = results.get(0);
	}
	terminateSession();
	terminateSessionFactory();
	return settingsConfiguration;
}
 
Example 14
@Override
public long countAnalyticalObjects( ProgramIndicator programIndicator )
{
    Query<Long> query = getTypedQuery( "select count(distinct c) from " + clazz.getName()
        + " c join c.dataDimensionItems d where d.programIndicator = :programIndicator" );
    query.setParameter( "dataSet", programIndicator );
    return query.uniqueResult();
}
 
Example 15
Source Project: Insights   Source File: DataTaggingDAL.java    License: Apache License 2.0 5 votes vote down vote up
public List<DataTagging> fetchEntityData(String hierarchyName) {
	Query<DataTagging> createQuery = getSession().createQuery(
			"FROM DataTagging DT WHERE DT.hierarchyName = :hierarchyName",
			DataTagging.class);
	createQuery.setParameter("hierarchyName", hierarchyName);
	List<DataTagging> resultList = createQuery.getResultList();
	terminateSession();
	terminateSessionFactory();
	return resultList;
}
 
Example 16
Source Project: Insights   Source File: ToolsLayoutDAL.java    License: Apache License 2.0 5 votes vote down vote up
public boolean saveToolLayout(String toolName, String toolCategory, JsonObject toolLayoutSettingJson) {
	Query<ToolsLayout> createQuery = getSession().createQuery(
			"FROM ToolsLayout a WHERE a.toolName = :toolName AND a.toolCategory = :toolCategory",
			ToolsLayout.class);
	createQuery.setParameter("toolName", toolName);
	createQuery.setParameter("toolCategory", toolCategory);
	List<ToolsLayout> resultList = createQuery.getResultList();
	ToolsLayout toolLayout = null;
	if(resultList.size()>0){
		toolLayout = resultList.get(0);
	}
	getSession().beginTransaction();
	if (toolLayout != null) {
		toolLayout.setSettingsJson(toolLayoutSettingJson.toString());
		getSession().update(toolLayout);
	} else {
		toolLayout = new ToolsLayout();
		toolLayout.setToolName(toolName);
		toolLayout.setToolCategory(toolCategory);
		toolLayout.setSettingsJson(toolLayoutSettingJson.toString());
		getSession().save(toolLayout);
	}
	getSession().getTransaction().commit();
	terminateSession();
	terminateSessionFactory();
	return true;
}
 
Example 17
@Test
public void selectLockAcquisitionTest() {
  // the translated statement must NOT show locking statements.
  testStatementTranslation(x -> {
    Query q = x.createQuery("select s from SubTestEntity s")
        .setFirstResult(8).setMaxResults(15);
    q.setLockMode(LockModeType.PESSIMISTIC_READ);
    q.list();
  }, "select subtestent0_.id as id1_1_, subtestent0_.id1 as id2_1_, "
      + "subtestent0_.id2 as id3_1_ from SubTestEntity subtestent0_ limit ? offset ?");
}
 
Example 18
@Override
public long countAnalyticalObjects( CategoryOptionGroup categoryOptionGroup )
{
    Query<Long> query = getTypedQuery( "select count(distinct c) from " + clazz.getName()
        + " c where :categoryOptionGroup in elements(c.categoryOptionGroups)" );
    query.setParameter( "categoryOptionGroup", categoryOptionGroup );
    return query.uniqueResult();
}
 
Example 19
Source Project: butterfly   Source File: EventSaveDataDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds an entry for an event for a user based on its event id.
 * @param user The user for the events
 * @param eventId The id of the event
 * @return The matching records
 */
public EventSaveData findByUserAndEventId(final UserProfile user, final int eventId) {
    final Query<EventSaveData> query = this.getCurrentSession().createQuery(
            "from EventSaveData where user = :user and eventId = :eventId")
            .setMaxResults(1);
    query.setParameter("user", user);
    query.setParameter("eventId", eventId);

    return query.getSingleResult();
}
 
Example 20
Source Project: butterfly   Source File: ProfileDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds a DDR profile by the dancer code.
 * @param dancerCode The dancer code for the profile
 * @return The profile for the given dancer code
 */
public UserProfile findByDancerCode(final int dancerCode) {
    final Query<UserProfile> query = this.getCurrentSession().createQuery("from UserProfile where dancer_code = :dancerCode");
    query.setParameter("dancerCode", dancerCode);

    return query.uniqueResult();
}
 
Example 21
@SuppressWarnings("rawtypes")
@Override
public int bulkUpdate(String expression, Object[] values) throws PersistenceException {
	if (!checkStoringAspect())
		return 0;

	try {
		Query queryObject = prepareQueryForUpdate("update " + entityClass.getCanonicalName() + " " + expression,
				values, null);
		return queryObject.executeUpdate();
	} catch (Throwable e) {
		throw new PersistenceException(e);
	}
}
 
Example 22
Source Project: lams   Source File: SessionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public org.hibernate.query.Query createFilter(Object collection, String queryString) {
	checkOpen();
	checkTransactionSynchStatus();
	CollectionFilterImpl filter = new CollectionFilterImpl(
			queryString,
			collection,
			this,
			getFilterQueryPlan( collection, queryString, null, false ).getParameterMetadata()
	);
	filter.setComment( queryString );
	delayedAfterCompletion();
	return filter;
}
 
Example 23
Source Project: yes-cart   Source File: GenericDAOHibernateImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public List<T> findAll() {
    final Query query = sessionFactory.getCurrentSession().createQuery(this.selectAllHql);
    return query.list();
}
 
Example 24
Source Project: butterfly   Source File: UserSongRecordDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all song records for a machine.
 * @param pcbid The PCBID of the machine to query for
 * @return A list of matching records
 */
public List<UserSongRecord> findByMachine(final String pcbid) {
    final Query<UserSongRecord> query = this.getCurrentSession().createQuery("from UserSongRecord r where r.machinePcbId = :pcbid");
    query.setParameter("pcbid", pcbid);

    return query.getResultList();
}
 
Example 25
Source Project: jeesupport   Source File: AbsSupportDao.java    License: MIT License 5 votes vote down vote up
@Override
public int executeByHQL( String _db , String _hql , String[] _param, Object[] _value ) {
	Session session = _get_session( _db );
	try {
		Query query = _get_session( _db ).createQuery( _hql );
		_set_parameter( query, _param, _value );
		return query.executeUpdate();
	} finally {
		_flush_session( session );
	}
}
 
Example 26
Source Project: lams   Source File: McUsrAttemptDAO.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
   public boolean isMcContentAttempted(Long mcContentUid) {
final String IS_USER_ATTEMPT_EXIST_BY_MC_CONTENT = "select COUNT(*) > 0 FROM " + McUsrAttempt.class.getName()
	+ " AS attempt WHERE attempt.mcQueContent.mcContent.uid=:mcContentUid";

Query<Boolean> q = getSession().createQuery(IS_USER_ATTEMPT_EXIST_BY_MC_CONTENT, Boolean.class);
q.setParameter("mcContentUid", mcContentUid);
return q.uniqueResult();
   }
 
Example 27
@Override
public List<TrackedEntityAttributeValue> searchByValue( TrackedEntityAttribute attribute, String searchText )
{
    String query = " from TrackedEntityAttributeValue v where v.attribute =:attribute and lower(v.plainValue) like :searchText";

    Query<TrackedEntityAttributeValue> typedQuery = getQuery( query )
        .setParameter( "attribute", attribute )
        .setParameter( "searchText", "%" + StringUtils.lowerCase( searchText  ) + "%");

    return getList( typedQuery );
}
 
Example 28
Source Project: butterfly   Source File: CardDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds a card by its ref ID.
 * @param refId The ref ID to query for.
 * @return The matching Card, or null if none are found.
 */
public Card findByRefId(final String refId) {
    final Query<Card> query = this.getCurrentSession().createQuery("from Card where ref_id = :refId");
    query.setParameter("refId", refId);

    return query.uniqueResult();
}
 
Example 29
Source Project: jeesupport   Source File: AbsSupportDao.java    License: MIT License 5 votes vote down vote up
@Override
@SuppressWarnings( "unchecked" )
public < T > List< T > selectByHQL( String _db , String _hql , int _first , int _limit , String[] _param , Object[] _value,
				Class< T > _cls ) {
	Session session = _get_session( _db );
	Query< T > query = session.createQuery( _hql );
	query.setFirstResult( _first );
	query.setMaxResults( _limit );

	_set_parameter( query, _param, _value );
	return query.getResultList();
}
 
Example 30
Source Project: tutorials   Source File: NamedParameterUnitTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = org.hibernate.QueryException.class)
public void whenNamedParameterMissing_thenThrowsQueryException() {
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    Query<Event> query = session.createQuery("from Event E WHERE E.title = :eventTitle", Event.class);

    try {
        query.list();
        fail("We are expecting an exception!");
    } finally {
        session.getTransaction().commit();
        session.close();
    }
}