Java Code Examples for org.hibernate.Query#uniqueResult()

The following examples show how to use org.hibernate.Query#uniqueResult() . 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 File: MessageForumsForumManagerImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public Topic getTopicByIdWithAttachments(final Long topicId) {

        if (topicId == null) {
            throw new IllegalArgumentException("Null Argument");
        }

        log.debug("getTopicByIdWithMessagesAndAttachments executing with topicId: " + topicId);

        HibernateCallback<Topic> hcb = session -> {
            Query q = session.getNamedQuery(QUERY_BY_TOPIC_ID_MESSAGES_ATTACHMENTS);
            q.setLong("id", topicId);
            return (Topic) q.uniqueResult();
        };

        // unproxy to avoid ClassCastException in certain scenarios
        return (Topic) HibernateUtils.unproxy(getHibernateTemplate().execute(hcb));

    }
 
Example 2
Source File: SbiMetaTableDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public SbiMetaTable loadTableByNameAndSource(Session session, String name, Integer sourceId) throws EMFUserError {
	logger.debug("IN");

	SbiMetaTable toReturn = null;
	Session tmpSession = session;

	try {
		// Criterion labelCriterrion = Expression.eq("name", name);
		// Criteria criteria = tmpSession.createCriteria(SbiMetaTable.class);
		// criteria.add(labelCriterrion);
		// toReturn = (SbiMetaTable) criteria.uniqueResult();

		String hql = " from SbiMetaTable c where c.name = ? and c.sbiMetaSource.sourceId = ? ";
		Query aQuery = tmpSession.createQuery(hql);
		aQuery.setString(0, name);
		aQuery.setInteger(1, sourceId);
		toReturn = (SbiMetaTable) aQuery.uniqueResult();
	} catch (HibernateException he) {
		logException(he);
		throw new HibernateException(he);
	} finally {
		logger.debug("OUT");
	}
	return toReturn;
}
 
Example 3
Source File: MessageForumsForumManagerImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public int getNumModTopicCurrentUserHasModPermForWithPermissionLevel(final List membershipList)
{
	if (membershipList == null) {
           log.error("getNumModTopicCurrentUserHasModPermForWithPermissionLevel failed with membershipList: null");
           throw new IllegalArgumentException("Null Argument");
       }

       log.debug("getNumModTopicCurrentUserHasModPermForWithPermissionLevel executing with membershipItems: " + membershipList);

       // hibernate will not like an empty list so return 0
       if (membershipList.isEmpty()) return 0;

       HibernateCallback<Number> hcb = session -> {
              Query q = session.getNamedQuery(QUERY_GET_NUM_MOD_TOPICS_WITH_MOD_PERM_BY_PERM_LEVEL);
              q.setParameterList("membershipList", membershipList);
              q.setString("contextId", getContextId());
              return (Number) q.uniqueResult();
          };

       return getHibernateTemplate().execute(hcb).intValue();
}
 
Example 4
Source File: ExtendedTimeQueries.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ExtendedTime getPubAndX(final String query, final PublishedAssessmentIfc pub, final String secondParam, final String secondParamValue) {
    try{
        HibernateCallback hcb = (Session s) -> {
            Query q = s.getNamedQuery(query);
            q.setParameter(PUBLISHED_ID, pub, new ManyToOneType(null, "org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAssessmentData"));
            q.setParameter(secondParam, secondParamValue, new StringType());
            return q.uniqueResult();
        };

        return (ExtendedTime) getHibernateTemplate().execute(hcb);
    } catch (DataAccessException e) {
        log.error("Failed to get extended time for pub: " + pub.getPublishedAssessmentId() + " and user/group: " + secondParamValue, e);
        return null;
    }
}
 
Example 5
Source File: I18NMessagesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public SbiI18NMessages getSbiI18NMessageById(Integer id) {
	logger.debug("IN");
	Session session = null;
	SbiI18NMessages toReturn = null;
	try {
		session = getSession();
		String hql = "from SbiI18NMessages m where m.id = :id";
		Query query = session.createQuery(hql);
		query.setInteger("id", id);
		toReturn = (SbiI18NMessages) query.uniqueResult();
	} catch (HibernateException e) {
		logException(e);
		throw new RuntimeException();
	} finally {
		if (session != null) {
			if (session.isOpen())
				session.close();
		}
	}
	logger.debug("OUT");
	return toReturn;
}
 
Example 6
Source File: PermissionManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public ControlPermissions getAreaControlPermissionByRoleAndType(final String roleId, final String typeId, final boolean defaultValue) {
    log.debug("getAreaControlPermissionByRole executing for current user: " + getCurrentUser());
    final Area area = areaManager.getAreaByContextIdAndTypeId(typeId);
    if (area == null) {
        return null;
    }
    HibernateCallback<ControlPermissions> hcb = session -> {
        Query q = session.getNamedQuery(QUERY_CP_BY_ROLE);
        q.setParameter("roleId", roleId, StringType.INSTANCE);
        q.setParameter("areaId", area.getId().toString(), StringType.INSTANCE);
        q.setParameter("defaultValue", defaultValue, BooleanType.INSTANCE);
        return (ControlPermissions) q.uniqueResult();
    };
    return getHibernateTemplate().execute(hcb);
}
 
Example 7
Source File: QuestionPoolFacadeQueries.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public long getSubPoolSize(final Long poolId) {
 final HibernateCallback<Number> hcb = session -> {
        Query q = session.createQuery("select count(qpp) from QuestionPoolData qpp where qpp.parentPoolId = :id");
        q.setCacheable(true);
        q.setLong("id", poolId);
        return (Number) q.uniqueResult();
    };
 
 return getHibernateTemplate().execute(hcb).longValue();
}
 
Example 8
Source File: TypeManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see org.sakaiproject.service.common.type.TypeManager#getType(java.lang.String, java.lang.String, java.lang.String)
 */
public Type getType(final String authority, final String domain, final String keyword)
{
	if (log.isDebugEnabled())
	{
		log.debug("getType(String " + authority + ", String " + domain + ", String " + keyword + ")");
	}
	// validation
	if (authority == null || authority.length() < 1) throw new IllegalArgumentException("authority");
	if (domain == null || domain.length() < 1) throw new IllegalArgumentException("domain");
	if (keyword == null || keyword.length() < 1) throw new IllegalArgumentException("keyword");

	final HibernateCallback hcb = new HibernateCallback()
	{
		public Object doInHibernate(Session session) throws HibernateException
		{
			Query q = session.getNamedQuery(FINDTYPEBYTUPLE);
			q.setString(AUTHORITY, authority);
			q.setString(DOMAIN, domain);
			q.setString(KEYWORD, keyword);
			q.setCacheable(cacheFindTypeByTuple);
			q.setCacheRegion(Type.class.getCanonicalName());
			return q.uniqueResult();
		}
	};
	Type type = (Type) getHibernateTemplate().execute(hcb);
	return type;
}
 
Example 9
Source File: PolicyDAO.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
   public boolean isPolicyConsentRequiredForUser(Integer userId) {
String SQL = "SELECT count(*) FROM lams_policy as policy" + " LEFT JOIN lams_policy_consent as policyConsent"
	+ " ON policy.uid = policyConsent.policy_uid AND policyConsent.user_id = :userId"
	+ " WHERE policyConsent.uid IS NULL AND policy.policy_state_id=1";

Query query = getSession().createSQLQuery(SQL);
query.setInteger("userId", userId);
Object value = query.uniqueResult();
int result = ((Number) value).intValue();

return result > 0;
   }
 
Example 10
Source File: SpagoBIInitializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
protected SbiProductTypeEngine findProductEngineType(Session aSession, String engine, String productType) {
	logger.debug("IN");
	String hql = "from SbiProductTypeEngine p where p.sbiEngines.label = :engine and p.sbiProductType.label = :productLabel";
	Query hibQuery = aSession.createQuery(hql);
	hibQuery.setString("engine", engine);
	hibQuery.setString("productLabel", productType);
	SbiProductTypeEngine result = (SbiProductTypeEngine) hibQuery.uniqueResult();
	logger.debug("OUT");
	return result;
}
 
Example 11
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public MessageThread getMessageThread(final String threadId) {
	
	final HibernateCallback<MessageThread> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_MESSAGE_THREAD);
           q.setParameter(ID, threadId, StringType.INSTANCE);
           q.setMaxResults(1);
           return (MessageThread) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 12
Source File: DaoSupportImpl.java    From JavaEE-SSH-Template with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public PageBean getPageBean(int pageNum, int pageSize,
		QueryHelper queryHelper) {
	System.out.println("-------> DaoSupportImpl.getPageBean( int pageNum, int pageSize, QueryHelper queryHelper )");

	// 参数列表
	List<Object> parameters = queryHelper.getParameters();

	// 查询本页的数据列表
	Query listQuery = getSession().createQuery(queryHelper.getListQueryHql()); // 创建查询对象
	if (parameters != null) { // 设置参数
		for (int i = 0; i < parameters.size(); i++) {
			listQuery.setParameter(i, parameters.get(i));
		}
	}
	listQuery.setFirstResult((pageNum - 1) * pageSize);
	listQuery.setMaxResults(pageSize);
	List list = listQuery.list(); // 执行查询

	// 查询总记录数量
	Query countQuery = getSession().createQuery(queryHelper.getCountQueryHql());
	if (parameters != null) { // 设置参数
		for (int i = 0; i < parameters.size(); i++) {
			countQuery.setParameter(i, parameters.get(i));
		}
	}
	Long count = (Long) countQuery.uniqueResult(); // 执行查询

	return new PageBean(pageNum, pageSize, count.intValue(), list);
}
 
Example 13
Source File: HibernateTest.java    From maven-framework-project with MIT License 5 votes vote down vote up
@Test @Transactional
public void updateAccount() {
    Session session = sessionFactory.getCurrentSession();
    Query query = session.createQuery("from Account a");
    Account a = (Account) query.uniqueResult();
    log.debug(a);
}
 
Example 14
Source File: PrivateMessageManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Area getAreaByContextIdAndTypeId(final String typeId) {
  log.debug("getAreaByContextIdAndTypeId executing for current user: " + getCurrentUser());
  HibernateCallback<Area> hcb = session -> {
      Query q = session.getNamedQuery("findAreaByContextIdAndTypeId");
      q.setParameter("contextId", getContextId(), StringType.INSTANCE);
      q.setParameter("typeId", typeId, StringType.INSTANCE);
      return (Area) q.uniqueResult();
  };

  return getHibernateTemplate().execute(hcb);
}
 
Example 15
Source File: ReadWriteTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testQuery() {
    Statistics stats = sessionFactory().getStatistics();

    Session s = openSession();
    s.beginTransaction();
    ItemReadWrite item = new ItemReadWrite("data");
    item.getEntries().addAll(Arrays.asList("a", "b", "c"));
    s.save(item);
    s.flush();
    s.getTransaction().commit();
    
    s = openSession();
    s.beginTransaction();
    Query query = s.getNamedQuery("testQuery");
    query.setCacheable(true);
    query.setCacheRegion("myTestQuery");
    query.setParameter("name", "data");
    item = (ItemReadWrite) query.uniqueResult();
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getPutCount());

    s = openSession();
    s.beginTransaction();
    Query query2 = s.getNamedQuery("testQuery");
    query2.setCacheable(true);
    query2.setCacheRegion("myTestQuery");
    query2.setParameter("name", "data");
    item = (ItemReadWrite) query2.uniqueResult();
    s.delete(item);
    s.getTransaction().commit();
    s.close();
    
    Assert.assertEquals(1, stats.getSecondLevelCacheStatistics("myTestQuery").getHitCount());
    
    stats.logSummary();
    
}
 
Example 16
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public SocialNetworkingInfo getSocialNetworkingInfo(final String userId) {
	
	final HibernateCallback<SocialNetworkingInfo> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_SOCIAL_NETWORKING_INFO);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           q.setMaxResults(1);
           return (SocialNetworkingInfo) q.uniqueResult();
     };

	return getHibernateTemplate().execute(hcb);
}
 
Example 17
Source File: DataSetDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns the Higher Version Number of a selected DS
 *
 * @param dsId the a data set ID
 * @throws EMFUserError the EMF user error
 */
@Override
public Integer getHigherVersionNumForDS(Integer dsId) {
	logger.debug("IN");
	Session session = null;
	Transaction transaction = null;
	Integer toReturn = null;
	try {
		session = getSession();
		transaction = session.beginTransaction();
		if (dsId != null) {
			Query hibQuery = session.createQuery("select max(h.id.versionNum) from SbiDataSet h where h.id.dsId = ?");
			hibQuery.setInteger(0, dsId);
			toReturn = (Integer) hibQuery.uniqueResult();
		}
	} catch (Throwable t) {
		if (transaction != null && transaction.isActive()) {
			transaction.rollback();
		}
		throw new SpagoBIDAOException("Error while modifing the data Set with id " + ((dsId == null) ? "" : String.valueOf(dsId)), t);
	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
		logger.debug("OUT");
	}
	return toReturn;
}
 
Example 18
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public ExternalIntegrationInfo getExternalIntegrationInfo(final String userUuid) {
			
	final HibernateCallback<ExternalIntegrationInfo> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_EXTERNAL_INTEGRATION_INFO);
           q.setParameter(USER_UUID, userUuid, StringType.INSTANCE);
           q.setMaxResults(1);
           return (ExternalIntegrationInfo) q.uniqueResult();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 19
Source File: BaseDaoImpl.java    From SpringCloud with Apache License 2.0 4 votes vote down vote up
public Object Queryobject(String hql, Object[] args, Map<String, Object> alias) {
    Query query = getSession().createQuery(hql);
    setAliasParameter(query, alias);
    setParameter(query, args);
    return query.uniqueResult();
}
 
Example 20
Source File: UserDaoImpl.java    From java-course-ee with MIT License 4 votes vote down vote up
public User getByLogin(String login) {
    final Query query = sessionFactory.getCurrentSession().createQuery("from User u where u.login = ?");
    query.setParameter(1, login);
    return (User)query.uniqueResult();
}