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

The following examples show how to use org.hibernate.Criteria#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: DBQueryUtil.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * Get the previous days number of apis for a particular component
 * 
 * @return int
 */
private static int getPreiousNumApis(final int compId, final Date date, final int envId) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	cal.add(Calendar.DATE, -1);
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria ctrStsCrit = session.createCriteria(ApiStatusEntity.class, "as");
	ctrStsCrit.add(Restrictions.eq("as.component.componentId",compId));
	ctrStsCrit.add(Restrictions.eq("as.environment.environmentId",envId));
	ctrStsCrit.add(Restrictions.eq("as.statusDate", new java.sql.Date(cal.getTimeInMillis())  ));
	ctrStsCrit.setMaxResults(1);
	ApiStatusEntity apiSts =(ApiStatusEntity) ctrStsCrit.uniqueResult();
	int totalApi = 0;
	if(apiSts != null){
		totalApi = apiSts.getTotalApi();
	}
	txn.commit();
	return totalApi;
}
 
Example 2
Source File: ContainerStatusDaoImpl.java    From kardio with Apache License 2.0 6 votes vote down vote up
@Override
public long getCurrentNumberOfContainsers(int envId,String componentIdsStrg, boolean isParentComponents) throws ParseException {
	
	List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);

	Session session = sessionFactory.openSession();
	DetachedCriteria subMaxDate = DetachedCriteria.forClass(ContainerStatusEntity.class);
	subMaxDate.setProjection(Projections.max("statsDate"));
	Criteria crtCurrentCont = session.createCriteria(ContainerStatusEntity.class, "contSts");
	crtCurrentCont.createCriteria("contSts.component", "component");
	crtCurrentCont.add(Property.forName("statsDate").eq(subMaxDate));
	
	DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, crtCurrentCont);

	crtCurrentCont.setProjection(Projections.sum("totalContainer"));
	long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long)0 : crtCurrentCont.uniqueResult());
	session.close();
	return currentNumOfCont;
	
}
 
Example 3
Source File: K8sPodsStatusDaoImpl.java    From kardio with Apache License 2.0 6 votes vote down vote up
@Override
public long getCurrentNumberOfPods(int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
	
	List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
	
	Session session = sessionFactory.openSession();
	DetachedCriteria subMaxDate = DetachedCriteria.forClass(K8sPodsContainersEntity.class);
	subMaxDate.setProjection(Projections.max("statusDate"));
	Criteria crtCurrentCont = session.createCriteria(K8sPodsContainersEntity.class, "contSts");
	crtCurrentCont.createCriteria("contSts.component", "component");
	crtCurrentCont.add(Property.forName("statusDate").eq(subMaxDate));
	
	DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, crtCurrentCont);

	crtCurrentCont.setProjection(Projections.sum("totalPods"));
	long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long)0 : crtCurrentCont.uniqueResult());
	session.close();
	return currentNumOfCont;
	
}
 
Example 4
Source File: ArticleService.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
public Article findUnique(Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(Article.class);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    criteria.setCacheable(true);
    return (Article)criteria.uniqueResult();
}
 
Example 5
Source File: ServerFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find contact method type by a given label.
 * @param label label of the contact method
 * @return contact method with the given label
 */
public static ContactMethod findContactMethodByLabel(String label) {
    Session session = getSession();
    Criteria criteria = session.createCriteria(ContactMethod.class);
    criteria.add(Restrictions.eq("label", label));
    return (ContactMethod) criteria.uniqueResult();
}
 
Example 6
Source File: CollectionRepositoryImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Boolean exist(String code) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.add(Restrictions.eq("code", code));
	criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
	Collection collection = (Collection) criteria.uniqueResult();
	return collection != null;
}
 
Example 7
Source File: HibernateDao.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public T findFirst(String orderByProperty, boolean isAsc,
		Criterion... criterions) {
	Criteria c = createCriteria(criterions);
	if (isAsc) {
		c.addOrder(Order.asc(orderByProperty));
	} else {
		c.addOrder(Order.desc(orderByProperty));
	}
	c.setMaxResults(1);
	return (T) c.uniqueResult();
}
 
Example 8
Source File: SbiMetaBcAttributeDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load BCAttribute by name.
 *
 * @param name
 *            the BCAttribute name
 *
 * @return the meta BCAttribute
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaBcAttributeDAOHibImpl#loadBcAttributeByName(string)
 */
@Override
public SbiMetaBcAttribute loadBcAttributeByName(String name) throws EMFUserError {
	logger.debug("IN");

	SbiMetaBcAttribute toReturn = null;
	Session tmpSession = null;
	Transaction tx = null;

	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		Criterion labelCriterrion = Expression.eq("name", name);
		Criteria criteria = tmpSession.createCriteria(SbiMetaBcAttribute.class);
		criteria.add(labelCriterrion);
		toReturn = (SbiMetaBcAttribute) criteria.uniqueResult();
		if (toReturn == null)
			return null;
		tx.commit();

	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}
	}

	logger.debug("OUT");
	return toReturn;
}
 
Example 9
Source File: HibernateSystemInfoDao.java    From livingdoc-confluence with GNU General Public License v3.0 5 votes vote down vote up
@Override
public SystemInfo getSystemInfo() {
    final Criteria crit = sessionService.getSession().createCriteria(SystemInfo.class);
    crit.add(Property.forName("id").eq(SYSTEM_INFO));
    SystemInfo systemInfo = ( SystemInfo ) crit.uniqueResult();
    // crit.addOrder(Order.desc("id"));
    // List list = crit.list();
    // SystemInfo systemInfo = null;
    // if (list.size() > 0) {
    // systemInfo = (SystemInfo) list.get(0);
    // }
    HibernateLazyInitializer.init(systemInfo);
    return systemInfo;
}
 
Example 10
Source File: AppResource.java    From maven-framework-project with MIT License 5 votes vote down vote up
/**
 * The @GET annotation causes this method to be invoked whenever an HTTP GET request is received for 
 * the registered URL. 
 */
@GET
public App getAppData( @PathParam("appId") Long appId ) {
	// Initialize Hibernate
	Configuration configuration = new Configuration();
	configuration.configure();
	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
	SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
	Session session = sessionFactory.openSession();
	session.beginTransaction();
	
	// Fetch an App for the given ID, using eager fetching.  The conversion to JSON happens after the 
	// Hibernate Session is closed... so if lazy fetching were used, then the JSON converter would fail 
	// when trying to access associated objects.
	Criteria criteria = session.createCriteria(App.class);
	criteria.add( Restrictions.eq("id", appId) );
	criteria.setFetchMode("supportedDevices", FetchMode.SELECT);
	criteria.setFetchMode("customerReviews", FetchMode.SELECT);
	App app = (App) criteria.uniqueResult();
	
	// Cleanup Hibernate
	session.getTransaction().commit();
	session.clear();
	session.close();
	sessionFactory.close();
	
	return app;
}
 
Example 11
Source File: LowFunctionalityDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load root low functionality.
 *
 * @param recoverBIObjects
 *            the recover bi objects
 *
 * @return the low functionality
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.analiticalmodel.functionalitytree.dao.ILowFunctionalityDAO#loadRootLowFunctionality(boolean)
 */
@Override
public LowFunctionality loadRootLowFunctionality(boolean recoverBIObjects) throws EMFUserError {
	logger.debug("IN");
	LowFunctionality funct = null;
	funct = getFromCache(ROOT);
	if (funct == null) {
		Session aSession = null;
		Transaction tx = null;
		try {
			aSession = getSession();
			tx = aSession.beginTransaction();
			/* ********* start luca changes *************** */
			// Criterion filters = Expression.isNull("parentFunct");
			Criterion filters = Expression.and(Expression.isNull("parentFunct"), Expression.eq("functTypeCd", "LOW_FUNCT"));
			/* ************ end luca changes ************** */
			Criteria criteria = aSession.createCriteria(SbiFunctions.class);
			criteria.add(filters);
			SbiFunctions hibFunct = (SbiFunctions) criteria.uniqueResult();
			if (hibFunct == null)
				return null;
			funct = toLowFunctionality(hibFunct, recoverBIObjects);
			tx.commit();
		} catch (HibernateException he) {
			logger.error("HibernateException", he);
			if (tx != null)
				tx.rollback();
			throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
		} finally {
			if (aSession != null) {
				if (aSession.isOpen())
					aSession.close();
			}
		}
		putIntoCache(ROOT, funct);
	}
	logger.debug("OUT");
	return funct;
}
 
Example 12
Source File: DefaultDao.java    From onedev with MIT License 5 votes vote down vote up
@Sessional
@Override
public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {
	Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
	criteria.setFirstResult(0);
	criteria.setMaxResults(1);
	return (T) criteria.uniqueResult();
}
 
Example 13
Source File: AbstractDAO.java    From flux with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves object by it's unique identifier.
 * @param cls - Class type of the object
 * @param id
 * @return (T) Object
 */
public T findById(Class cls, String id) {
    Criteria criteria = currentSession().createCriteria(cls).add(Restrictions.eq("id", id));
    Object object = criteria.uniqueResult();
    T castedObject = null;
    if(object != null)
        castedObject = (T) object;
    return castedObject;
}
 
Example 14
Source File: LowFunctionalityDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Exist by code.
 *
 * @param code
 *            the code
 *
 * @return the integer
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.analiticalmodel.functionalitytree.dao.ILowFunctionalityDAO#existByCode(java.lang.String)
 */
@Override
public Integer existByCode(String code) throws EMFUserError {
	Integer id = null;
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		Criterion domainCdCriterrion = Expression.eq("code", code);
		Criteria criteria = aSession.createCriteria(SbiFunctions.class);
		criteria.add(domainCdCriterrion);
		SbiFunctions func = (SbiFunctions) criteria.uniqueResult();
		if (func != null) {
			id = func.getFunctId();
		}
		tx.commit();
	} catch (HibernateException he) {
		logger.error("HibernateException", he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	return id;
}
 
Example 15
Source File: LowFunctionalityDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Saves all roles for a functionality, using session and permission information. The permission for a functionality can be DEVELOPMENT, TEST, EXECUTION AND
 * CREATE and each permission has its own roles.
 *
 * @param aSession
 *            The current session object
 * @param hibFunct
 *            The functionality hibernate object
 * @param aLowFunctionality
 *            The Low Functionality object
 * @param permission
 *            The string defining the permission
 * @return A collection object containing all roles
 * @throws EMFUserError
 *
 */
private Set saveRolesFunctionality(Session aSession, SbiFunctions hibFunct, LowFunctionality aLowFunctionality, String permission) throws EMFUserError {
	Set functRoleToSave = new HashSet();
	Criterion domainCdCriterrion = null;
	Criteria criteria = null;
	criteria = aSession.createCriteria(SbiDomains.class);
	domainCdCriterrion = Expression.and(Expression.eq("valueCd", permission), Expression.eq("domainCd", SpagoBIConstants.PERMISSION_ON_FOLDER));
	criteria.add(domainCdCriterrion);
	SbiDomains permissionDomain = (SbiDomains) criteria.uniqueResult();
	if (permissionDomain == null) {
		logger.error("The Domain with value_cd=" + permission + " and domain_cd=" + SpagoBIConstants.PERMISSION_ON_FOLDER + " does not exist.");
		throw new EMFUserError(EMFErrorSeverity.ERROR, 1039);
	}
	Role[] roles = null;
	if (permission.equalsIgnoreCase(SpagoBIConstants.PERMISSION_ON_FOLDER_TO_DEVELOP)) {
		roles = aLowFunctionality.getDevRoles();
	} else if (permission.equalsIgnoreCase(SpagoBIConstants.PERMISSION_ON_FOLDER_TO_TEST)) {
		roles = aLowFunctionality.getTestRoles();
	} else if (permission.equalsIgnoreCase(SpagoBIConstants.PERMISSION_ON_FOLDER_TO_EXECUTE)) {
		roles = aLowFunctionality.getExecRoles();
	} else if (permission.equalsIgnoreCase(SpagoBIConstants.PERMISSION_ON_FOLDER_TO_CREATE)) {
		roles = aLowFunctionality.getCreateRoles();
	}
	for (int i = 0; i < roles.length; i++) {
		Role role = roles[i];
		domainCdCriterrion = Expression.eq("name", role.getName());
		criteria = aSession.createCriteria(SbiExtRoles.class);
		criteria.add(domainCdCriterrion);
		SbiExtRoles hibRole = (SbiExtRoles) criteria.uniqueResult();
		SbiFuncRoleId sbifuncroleid = new SbiFuncRoleId();
		sbifuncroleid.setFunction(hibFunct);
		sbifuncroleid.setState(permissionDomain);
		sbifuncroleid.setRole(hibRole);
		SbiFuncRole sbifuncrole = new SbiFuncRole();
		sbifuncrole.setId(sbifuncroleid);
		sbifuncrole.setStateCd(permissionDomain.getValueCd());

		updateSbiCommonInfo4Update(sbifuncrole, true);

		aSession.save(sbifuncrole);
		functRoleToSave.add(sbifuncrole);
	}
	logger.debug("The [saveRolesFunctionality] occurs. LowFunctionality cache will be cleaned.");
	this.clearCache();
	return functRoleToSave;
}
 
Example 16
Source File: HibernateDao.java    From DWSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public T findFirst(Criterion... criterions) {
	Criteria c = createCriteria(criterions);
	c.setMaxResults(1);
	return (T) c.uniqueResult();
}
 
Example 17
Source File: GradebookManagerImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public Gradebook getGradebookByIdWithHeadingsAndStudents(final Long gradebookId) {
	if (gradebookId == null) {
        throw new IllegalArgumentException("Null gradebookId passed to getGradebookByIdWithStudents");
       }

	HibernateCallback hcb = session -> {

           Criteria crit = session.createCriteria(GradebookImpl.class).add(Expression.eq(ID, gradebookId));

           Gradebook gradebook = (Gradebook)crit.uniqueResult();
           getHibernateTemplate().initialize(gradebook.getHeadings());
           getHibernateTemplate().initialize(gradebook.getStudents());

           return gradebook;
       };

      return (Gradebook) getHibernateTemplate().execute(hcb); 

}
 
Example 18
Source File: CheckDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Modify check.
 *
 * @param check
 *            the check
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.check.dao.ICheckDAO#modifyCheck(it.eng.spagobi.behaviouralmodel.check.bo.Check)
 */
@Override
public void modifyCheck(Check check) throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	try {

		aSession = getSession();
		tx = aSession.beginTransaction();

		SbiChecks hibCheck = (SbiChecks) aSession.load(SbiChecks.class, check.getCheckId().intValue());

		Criteria criteria = aSession.createCriteria(SbiDomains.class);
		Criterion aCriterion = Restrictions.and(Restrictions.eq("valueId".trim(), check.getValueTypeId().intValue()),
				Restrictions.eq("valueCd".trim(), check.getValueTypeCd()).ignoreCase());

		criteria.add(aCriterion);

		SbiDomains aSbiDomains = (SbiDomains) criteria.uniqueResult();

		if (aSbiDomains == null) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, "CheckDAOHibImpl", "modifyCheck",
					"The Domain with value_id=" + check.getValueTypeId() + " and value_cd=" + check.getValueTypeCd() + " does not exist.");
			throw new EMFUserError(EMFErrorSeverity.ERROR, 1036);
		}

		hibCheck.setDescr(check.getDescription());
		hibCheck.setName(check.getName());
		hibCheck.setLabel(check.getLabel());
		hibCheck.setValue1(check.getFirstValue());
		hibCheck.setValue2(check.getSecondValue());
		hibCheck.setCheckType(aSbiDomains);
		hibCheck.setValueTypeCd(aSbiDomains.getValueCd());
		updateSbiCommonInfo4Update(hibCheck);
		tx.commit();

	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {

		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}

	}

}
 
Example 19
Source File: ChannelFactory.java    From uyuni with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns the Channel whose label matches the given label.
 * This was added to allow taskomatic to lookup channels by label,
 * and should NOT be used from the webui.
 * @param label Channel label sought.
 * @return the Channel whose label matches the given label.
 */
public static Channel lookupByLabel(String label) {
    Session session = getSession();
    Criteria c = session.createCriteria(Channel.class);
    c.add(Restrictions.eq("label", label));
    return (Channel) c.uniqueResult();
}
 
Example 20
Source File: HibernateSupportDao.java    From base-framework with Apache License 2.0 2 votes vote down vote up
/**
 * 通过orm实体的属性名称查询单个orm实体
 * 
 * @param propertyName 属性名称
 * @param value 值
 * @param restrictionName 约束名称 参考{@link CriterionBuilder}的所有实现类
 * 
 * @return Object
 */
public T findUniqueByProperty(String propertyName,Object value,String restrictionName) {
	Criterion criterion = HibernateRestrictionBuilder.getRestriction(propertyName, value, restrictionName);
	Criteria criteria = createCriteria(criterion);
	return (T) criteria.uniqueResult();
}