Example usage for org.hibernate.criterion Restrictions naturalId

List of usage examples for org.hibernate.criterion Restrictions naturalId

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions naturalId.

Prototype

public static NaturalIdentifier naturalId() 

Source Link

Document

Consider using any of the natural id based loading stuff from session instead, especially in cases where the restriction is the full set of natural id values.

Usage

From source file:com.eucalyptus.entities.EntityWrapper.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T> T getUnique(final T example) throws EucalyptusCloudException {
    try {/*from   w  w w.ja v  a 2 s  .  c om*/
        Object id = null;
        try {
            id = this.getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil()
                    .getIdentifier(example);
        } catch (final Exception ex) {
        }
        if (id != null) {
            final T res = (T) this.getEntityManager().find(example.getClass(), id);
            if (res == null) {
                throw new NoSuchElementException("@Id: " + id);
            } else {
                return res;
            }
        } else if ((example instanceof HasNaturalId) && (((HasNaturalId) example).getNaturalId() != null)) {
            final String natId = ((HasNaturalId) example).getNaturalId();
            final T ret = (T) this.createCriteria(example.getClass()).setLockMode(LockMode.NONE)
                    .setCacheable(true).setMaxResults(1).setFetchSize(1).setFirstResult(0)
                    .add(Restrictions.naturalId().set("naturalId", natId)).uniqueResult();
            if (ret == null) {
                throw new NoSuchElementException("@NaturalId: " + natId);
            }
            return ret;
        } else {
            final T ret = (T) this.createCriteria(example.getClass()).setLockMode(LockMode.NONE)
                    .setCacheable(true).setMaxResults(1).setFetchSize(1).setFirstResult(0)
                    .add(Example.create(example).enableLike(MatchMode.EXACT)).uniqueResult();
            if (ret == null) {
                throw new NoSuchElementException("example: " + LogUtil.dumpObject(example));
            }
            return ret;
        }
    } catch (final NonUniqueResultException ex) {
        throw new EucalyptusCloudException(
                "Get unique failed for " + example.getClass().getSimpleName() + " because " + ex.getMessage(),
                ex);
    } catch (final NoSuchElementException ex) {
        throw new EucalyptusCloudException(
                "Get unique failed for " + example.getClass().getSimpleName() + " using " + ex.getMessage(),
                ex);
    } catch (final Exception ex) {
        final Exception newEx = PersistenceExceptions.throwFiltered(ex);
        throw new EucalyptusCloudException("Get unique failed for " + example.getClass().getSimpleName()
                + " because " + newEx.getMessage(), newEx);
    }
}

From source file:com.eucalyptus.entities.EntityWrapper.java

License:Open Source License

/**
 * Returns the unique result from the database that exactly matches <code>example</code>. The differences between this method and {@link #getUnique(Object)} are:
 * <ol><li>{@link #getUnique(Object)} uses <i><code>enableLike</code></i> match and this method does not. <i><code>enableLike</code></i> criteria trips hibernate when 
 * special characters are involved. So it has been replaced by exact "=" (equals to)</li>  
 * <li>Unique result logic is correctly implemented in this method. If the query returns more than one result, this method correctly throws an exception 
 * wrapping <code>NonUniqueResultException</code>. {@link #getUnique(Object)} does not throw an exception in this case and returns a result as long as it finds
 * one or more matching results (because of the following properties set on the query: <code>setMaxResults(1)</code>, <code>setFetchSize(1)</code> and 
 * <code>setFirstResult(0)</code>)</li></ol>
 * /*w  w  w.j  a  v  a  2 s . co m*/
 * @param example
 * @return
 * @throws EucalyptusCloudException
 */
@SuppressWarnings("unchecked")
public <T> T getUniqueEscape(final T example) throws EucalyptusCloudException {
    try {
        Object id = null;
        try {
            id = this.getEntityManager().getEntityManagerFactory().getPersistenceUnitUtil()
                    .getIdentifier(example);
        } catch (final Exception ex) {
        }
        if (id != null) {
            final T res = (T) this.getEntityManager().find(example.getClass(), id);
            if (res == null) {
                throw new NoSuchElementException("@Id: " + id);
            } else {
                return res;
            }
        } else if ((example instanceof HasNaturalId) && (((HasNaturalId) example).getNaturalId() != null)) {
            final String natId = ((HasNaturalId) example).getNaturalId();
            final T ret = (T) this.createCriteria(example.getClass()).setLockMode(LockMode.NONE)
                    .setCacheable(true).add(Restrictions.naturalId().set("naturalId", natId)).uniqueResult();
            if (ret == null) {
                throw new NoSuchElementException("@NaturalId: " + natId);
            }
            return ret;
        } else {
            final T ret = (T) this.createCriteria(example.getClass()).setLockMode(LockMode.NONE)
                    .setCacheable(true).add(Example.create(example)).uniqueResult();
            if (ret == null) {
                throw new NoSuchElementException("example: " + LogUtil.dumpObject(example));
            }
            return ret;
        }
    } catch (final NonUniqueResultException ex) {
        throw new EucalyptusCloudException(
                "Get unique failed for " + example.getClass().getSimpleName() + " because " + ex.getMessage(),
                ex);
    } catch (final NoSuchElementException ex) {
        throw new EucalyptusCloudException(
                "Get unique failed for " + example.getClass().getSimpleName() + " using " + ex.getMessage(),
                ex);
    } catch (final Exception ex) {
        final Exception newEx = PersistenceExceptions.throwFiltered(ex);
        throw new EucalyptusCloudException("Get unique failed for " + example.getClass().getSimpleName()
                + " because " + newEx.getMessage(), newEx);
    }
}

From source file:com.expressui.core.dao.GenericDao.java

License:Open Source License

/**
 * Finds an entity by natural id, or business key. This method only works for entities that have a single property
 * marked as @NaturalId. The benefit of calling this method is that Hibernate will try to look up the entity
 * in the secondary cache.//from   w  ww  .  j  a v a2 s . c o  m
 *
 * @param entityType    the type of entity
 * @param propertyName  the name of the property in the entity that is marked @NaturalId
 * @param propertyValue the value to search for
 * @param <T>           type of entity
 * @return found entity
 */
public <T> T findByNaturalId(Class<? extends T> entityType, String propertyName, Object propertyValue) {
    Session session = (Session) getEntityManager().getDelegate();

    Criteria criteria = session.createCriteria(entityType);
    criteria.add(Restrictions.naturalId().set(propertyName, propertyValue));
    criteria.setCacheable(true);

    return (T) criteria.uniqueResult();
}

From source file:com.hmsinc.epicenter.model.geography.impl.GeographyRepositoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
public <T extends Geography> T getGeography(String name, Class<T> geographyType) {
    Validate.notNull(name, "Name must be specified.");
    final List<T> result = criteriaQuery(entityManager, geographyType)
            .add(Restrictions.naturalId().set("name", name)).list();
    return (result.size() > 0 ? result.get(0) : null);
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryCache.java

License:Open Source License

protected CachedItem getCachedItem(String uri, RepositoryCacheableItem cacheableItem,
        boolean clearPendingSavesCreatedByFindByCriteria, Session session) {
    if (log.isDebugEnabled()) {
        log.debug("HibernateRepositoryCache:  Looking in repository cache \"" + cacheableItem.getCacheName()
                + "\" for resource \"" + uri);
    }/*from   ww  w .  ja v a 2 s.c  o m*/

    DetachedCriteria criteria = DetachedCriteria.forClass(CachedItem.class);
    criteria.add(Restrictions.naturalId().set("cacheName", cacheableItem.getCacheName()).set("uri", uri));
    criteria.getExecutableCriteria(getSession()).setCacheable(true);
    List list = null;

    if (setFindByCriteriaToReadOnly) {
        // flush all pending saves, updates and deletes to the database (However, it may slows down the performance, since we have to synchronize the method
        list = findByCritera(criteria, clearPendingSavesCreatedByFindByCriteria);
    } else {
        // no synchronization, but spring hibernate template creates an extra update statement when calling findByCriteria
        if (session == null)
            list = getHibernateTemplate().findByCriteria(criteria);
        else
            list = criteria.getExecutableCriteria(session).list();
    }

    CachedItem item = null;
    if (list.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("did not find \"" + uri + "\" in cache " + cacheableItem.getCacheName());
        }
        item = null;
    } else {
        item = (CachedItem) list.get(0);
        if (log.isDebugEnabled()) {
            log.debug("found \"" + uri + "\" in cache " + cacheableItem.getCacheName() + ". isReference: "
                    + item.isItemReference());
        }
    }
    return item;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

protected RepoFolder getFolder(String uri, boolean required) {
    if (uri == null || uri.length() == 0 || uri.equals(Folder.SEPARATOR)) {
        return getRootFolder();
    }//from   w  ww  .  j av a  2  s.  c o m

    // Deal with URIs that come with "repo:" on the front

    final String repoURIPrefix = Resource.URI_PROTOCOL + ":";
    String workUri = uri.startsWith(repoURIPrefix) ? uri.substring(repoURIPrefix.length()) : uri;

    DetachedCriteria criteria = DetachedCriteria.forClass(RepoFolder.class);
    criteria.add(Restrictions.naturalId().set("URI", workUri));
    criteria.getExecutableCriteria(getSession()).setCacheable(true);
    List foldersList = getHibernateTemplate().findByCriteria(criteria);
    RepoFolder folder;
    if (foldersList.isEmpty()) {
        if (required) {
            String quotedURI = "\"" + uri + "\"";
            throw new JSResourceNotFoundException("jsexception.folder.not.found.at",
                    new Object[] { quotedURI });
        }

        log.debug("Folder not found at \"" + uri + "\"");
        folder = null;
    } else {
        folder = (RepoFolder) foldersList.get(0);
    }
    return folder;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

protected RepoFolder getRootFolder() {
    DetachedCriteria criteria = DetachedCriteria.forClass(RepoFolder.class);
    criteria.add(Restrictions.naturalId().set("URI", Folder.SEPARATOR));
    criteria.getExecutableCriteria(getSession()).setCacheable(true);
    List foldersList = getHibernateTemplate().findByCriteria(criteria);
    RepoFolder root;//ww w .ja va2  s .  c  o  m
    if (foldersList.isEmpty()) {
        root = null;
    } else {
        root = (RepoFolder) foldersList.get(0);
    }
    return root;
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

protected DetachedCriteria resourceNameCriteria(Class persistentClass, RepoFolder folder, String name) {
    DetachedCriteria criteria = DetachedCriteria.forClass(persistentClass);
    criteria.add(Restrictions.naturalId().set("name", name).set("parent", folder));
    return criteria;
}

From source file:com.jaspersoft.jasperserver.api.metadata.tenant.service.impl.TenantServiceImpl.java

License:Open Source License

private DetachedCriteria createSearchTenantsCriteria(String parentTenantId, String text) {
    DetachedCriteria criteria = DetachedCriteria.forClass(persistentTenantClass());

    criteria.createAlias("parent", "p");
    criteria.add(Restrictions.naturalId().set("p.tenantId", parentTenantId));

    if (text != null) {
        text = databaseCharactersEscapeResolver.getEscapedText(text.trim());
        if (text.length() > 0) {
            Disjunction disjunction = Restrictions.disjunction();

            //                disjunction.add(Restrictions.ilike("tenantId", "%" + text + "%"));
            //                disjunction.add(Restrictions.ilike("tenantAlias", "%" + text + "%"));
            //                disjunction.add(Restrictions.ilike("tenantName", "%" + text + "%"));
            //                disjunction.add(Restrictions.ilike("tenantDesc", "%" + text + "%"));

            disjunction.add(new IlikeEscapeAwareExpression("tenantId", text, MatchMode.ANYWHERE));
            disjunction.add(new IlikeEscapeAwareExpression("tenantAlias", text, MatchMode.ANYWHERE));
            disjunction.add(new IlikeEscapeAwareExpression("tenantName", text, MatchMode.ANYWHERE));
            disjunction.add(new IlikeEscapeAwareExpression("tenantDesc", text, MatchMode.ANYWHERE));

            criteria.add(disjunction);/*from   w w w.  j  a v  a 2s  . com*/
        }
    }

    return criteria;
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

License:Open Source License

protected RepoRole getRepoRole(String roleName, String tenantId) {
    RepoTenant tenant = getPersistentTenant(tenantId, false);
    if (tenant == null && !isNullTenant(tenantId)) {
        //if the requested tenant was not found, return null
        if (log.isDebugEnabled()) {
            log.debug("Tenant " + tenantId + " not found, returning null role");
        }//from   w  ww  . ja  va 2 s.co m
        return null;
    }

    DetachedCriteria criteria = DetachedCriteria.forClass(getPersistentRoleClass());
    if (tenant == null) {
        criteria.add(Restrictions.isNull("tenant")).add(Restrictions.eq("roleName", roleName));
    } else {
        criteria.add(Restrictions.naturalId().set("tenant", tenant).set("roleName", roleName));
    }
    List roleList = getHibernateTemplate().findByCriteria(criteria);
    RepoRole role = null;
    if (roleList.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Role not found with role name \"" + roleName + "\""
                    + (tenantId == null ? "" : (", tenant \"" + tenantId + "\"")));
        }
    } else {
        role = (RepoRole) roleList.get(0);
    }
    return role;
}