Example usage for org.hibernate.criterion Restrictions not

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

Introduction

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

Prototype

public static Criterion not(Criterion expression) 

Source Link

Document

Return the negation of an expression

Usage

From source file:org.ambraproject.article.service.IngesterImpl.java

License:Apache License

/**
 * Add/update reciprocal related article links.  There are two situations in which this is relevant: <ol> <li> We are
 * ingesting Article B. Article A already exists, and relates to Article B. We need to update Article A's relationship
 * to set the 'otherArticleID' property, and make sure that Article B has a link back to Article A. </li> <li> We
 * ingesting Article B, which has a relationship pointing to Article A.  Article A already exists. We need to make
 * sure Article A has a link back to Article B, and update the 'otherArticleID' property on both of the relationships.
 * </li> </ol>//from   w w w .  ja  v a 2  s. c o  m
 *
 * @param newArticle The Article which is being ingested
 */
@SuppressWarnings("unchecked")
private void addReciprocalRelatedArticleAssociations(Article newArticle) {
    //keep track of the other articles we already updated
    Set<String> otherArticleDois = new HashSet<String>(newArticle.getRelatedArticles().size());

    //For each of the articles that the new one links to, update the reciprocal relations
    for (ArticleRelationship relationship : newArticle.getRelatedArticles()) {
        otherArticleDois.add(relationship.getOtherArticleDoi());
        Article otherArticle;
        //Set the 'otherArticleID' property for any new relationships created by this article
        try {
            otherArticle = (Article) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class)
                    .add(Restrictions.eq("doi", relationship.getOtherArticleDoi())), 0, 1).get(0);
        } catch (IndexOutOfBoundsException e) {
            //other article didn't exist
            continue;
        }
        relationship.setOtherArticleID(otherArticle.getID());
        hibernateTemplate.update(relationship);

        //Now ensure that there is a reciprocal link, i.e. that the 'other article' links back to the new one
        boolean createNewRelationship = true;
        //so we have to check if the other article already has a link to this one
        for (ArticleRelationship otherArticleRelationship : otherArticle.getRelatedArticles()) {
            if (otherArticleRelationship.getOtherArticleDoi().equals(newArticle.getDoi())) {
                createNewRelationship = false;
                otherArticleRelationship.setOtherArticleID(newArticle.getID());
                hibernateTemplate.update(otherArticleRelationship);
                break;
            }
        }
        //if the other article didn't already have a link to this one, we need to make a new one
        if (createNewRelationship) {
            ArticleRelationship reciprocalLink = new ArticleRelationship();
            reciprocalLink.setParentArticle(otherArticle);
            reciprocalLink.setOtherArticleID(newArticle.getID());
            reciprocalLink.setOtherArticleDoi(newArticle.getDoi());
            reciprocalLink.setType(relationship.getType());
            otherArticle.getRelatedArticles().add(reciprocalLink);
            hibernateTemplate.update(otherArticle);
        }
    }

    //Now we need to find any existing articles that link to the new one, (that we didn't just update) and update the relationships
    List<Article> articlesLinkingToNewOne;
    if (!otherArticleDois.isEmpty()) {
        //articles linking to this one that we didn't already visit
        articlesLinkingToNewOne = hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Article.class)
                .add(Restrictions.not(Restrictions.in("doi", otherArticleDois)))
                .createCriteria("relatedArticles")
                .add(Restrictions.eq("otherArticleDoi", newArticle.getDoi())));
    } else {
        //hibernate throws a sql grammar exception if you do a restrictions.in() with an empty collection
        articlesLinkingToNewOne = hibernateTemplate
                .findByCriteria(DetachedCriteria.forClass(Article.class).createCriteria("relatedArticles")
                        .add(Restrictions.eq("otherArticleDoi", newArticle.getDoi())));
    }
    for (Article otherArticle : articlesLinkingToNewOne) {
        //update the other article's relationship
        for (ArticleRelationship otherRelationship : otherArticle.getRelatedArticles()) {
            if (otherRelationship.getOtherArticleDoi().equals(newArticle.getDoi())) {
                otherRelationship.setOtherArticleID(newArticle.getID());
                hibernateTemplate.update(otherRelationship);
                //create a relationship linking to the other article
                ArticleRelationship relationship = new ArticleRelationship();
                relationship.setParentArticle(newArticle);
                relationship.setOtherArticleID(otherArticle.getID());
                relationship.setOtherArticleDoi(otherArticle.getDoi());
                relationship.setType(otherRelationship.getType());
                newArticle.getRelatedArticles().add(relationship);
            }
        }
    }
    //if we added new relationships, update the new article
    if (articlesLinkingToNewOne.size() > 0) {
        hibernateTemplate.update(newArticle);
    }
}

From source file:org.ambraproject.user.service.UserServiceImpl.java

License:Apache License

@Override
@Transactional(rollbackFor = { Throwable.class })
public UserProfile saveOrUpdateUser(final UserProfile userProfile) throws DuplicateDisplayNameException {
    //even if you're updating a user, it could be a user with no display name. so we need to make sure they don't pick one that already exists
    Long count = (Long) hibernateTemplate.findByCriteria(DetachedCriteria.forClass(UserProfile.class)
            .add(Restrictions.eq("displayName", userProfile.getDisplayName()))
            .add(Restrictions.not(Restrictions.eq("authId", userProfile.getAuthId())))
            .setProjection(Projections.rowCount()), 0, 1).get(0);
    if (!count.equals(0l)) {
        throw new DuplicateDisplayNameException();
    }//from   w  w w  .  ja  v  a 2s  .co  m
    //check if a user with the same auth id already exists
    UserProfile existingUser = getUserByAuthId(userProfile.getAuthId());
    if (existingUser != null) {
        log.debug("Found a user with authID: {}, updating profile", userProfile.getAuthId());
        copyFields(userProfile, existingUser);
        hibernateTemplate.update(existingUser);
        return existingUser;
    } else {
        log.debug("Creating a new user with authID: {}; {}", userProfile.getAuthId(), userProfile);
        //TODO: We're generating account and profile uris here to maintain backwards compatibility with annotations
        //once those are refactored we can just call hibernateTemplate.save()
        String prefix = System.getProperty(ConfigurationStore.SYSTEM_OBJECT_ID_PREFIX);
        String accountUri = prefix + "account/" + UUID.randomUUID().toString();
        String profileUri = prefix + "profile/" + UUID.randomUUID().toString();
        userProfile.setAccountUri(accountUri);
        userProfile.setProfileUri(profileUri);
        hibernateTemplate.save(userProfile);
        return userProfile;
    }
}

From source file:org.balisunrise.daa.hibernate.HCriteria.java

License:Open Source License

private org.hibernate.criterion.Criterion makeCriterion(Criterion.Junction junction) {

    List<org.hibernate.criterion.Criterion> hcs = new LinkedList<>();
    for (Criterion criterion : junction.getCriterions()) {
        org.hibernate.criterion.Criterion hc = makeCriterion(criterion);
        if (hc != null)
            hcs.add(hc);/*from  w ww  .  j  a v  a2 s.co m*/
    }

    if (hcs.isEmpty())
        return null;
    if (hcs.size() == 1)
        return hcs.get(0);

    org.hibernate.criterion.Criterion[] array = (org.hibernate.criterion.Criterion[]) hcs.toArray();

    if (junction.getLogicType() == Query.LogicType.OR)
        return Restrictions.or(array);
    else {
        org.hibernate.criterion.Criterion hc = Restrictions.and(array);
        if (junction.getLogicType() == Query.LogicType.NOT)
            return Restrictions.not(hc);
        return hc;
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.query.AbstractHibernateCriterionAdapter.java

License:Apache License

protected void addJunctionCriterionAdapters() {
    criterionAdaptors.put(Query.Conjunction.class, new CriterionAdaptor<Query.Conjunction>() {
        @Override/*ww w.  java  2 s .  c  o  m*/
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                Query.Conjunction criterion, String alias) {
            Conjunction conjunction = Restrictions.conjunction();
            applySubCriteriaToJunction(hibernateQuery.getEntity(), hibernateQuery, criterion.getCriteria(),
                    conjunction, alias);
            return conjunction;
        }
    });
    criterionAdaptors.put(Query.Disjunction.class, new CriterionAdaptor<Query.Disjunction>() {
        @Override
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery,
                Query.Disjunction criterion, String alias) {
            Disjunction disjunction = Restrictions.disjunction();
            applySubCriteriaToJunction(hibernateQuery.getEntity(), hibernateQuery, criterion.getCriteria(),
                    disjunction, alias);
            return disjunction;
        }
    });
    criterionAdaptors.put(Query.Negation.class, new CriterionAdaptor<Query.Negation>() {
        @Override
        public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.Negation criterion,
                String alias) {
            CriterionAdaptor<Query.Disjunction> adapter = (CriterionAdaptor<Query.Disjunction>) criterionAdaptors
                    .get(Query.Disjunction.class);
            return Restrictions.not(adapter.toHibernateCriterion(hibernateQuery,
                    new Query.Disjunction(criterion.getCriteria()), alias));
        }
    });
}

From source file:org.codehaus.groovy.grails.orm.hibernate.query.AbstractHibernateQuery.java

License:Apache License

@Override
public Junction negation() {
    final org.hibernate.criterion.Disjunction disjunction = Restrictions.disjunction();
    addToCriteria(Restrictions.not(disjunction));
    return new HibernateJunction(disjunction, alias);
}

From source file:org.codehaus.groovy.grails.orm.hibernate.query.HibernateQuery.java

License:Apache License

@Override
public Junction negation() {
    final org.hibernate.criterion.Disjunction disjunction = Restrictions.disjunction();
    criteria.add(Restrictions.not(disjunction));
    return new HibernateJunction(disjunction);
}

From source file:org.dspace.authorize.dao.impl.ResourcePolicyDAOImpl.java

License:BSD License

@Override
public List<ResourcePolicy> findByTypeIdGroupAction(Context context, DSpaceObject dso, Group group, int action,
        int notPolicyID) throws SQLException {
    Criteria criteria = createCriteria(context, ResourcePolicy.class);
    criteria.add(Restrictions.and(Restrictions.eq("dSpaceObject", dso), Restrictions.eq("epersonGroup", group),
            Restrictions.eq("actionId", action)));
    criteria.setMaxResults(1);//from  ww w.  ja  v  a  2 s. c o m

    List<ResourcePolicy> results;
    if (notPolicyID != -1) {
        criteria.add(Restrictions.and(Restrictions.not(Restrictions.eq("id", action))));
    }

    return list(criteria);
}

From source file:org.dspace.content.dao.impl.BitstreamDAOImpl.java

License:BSD License

@Override
public List<Bitstream> findDuplicateInternalIdentifier(Context context, Bitstream bitstream)
        throws SQLException {
    Criteria criteria = createCriteria(context, Bitstream.class);
    criteria.add(Restrictions.and(Restrictions.eq("internalId", bitstream.getInternalId()),
            Restrictions.not(Restrictions.eq("id", bitstream.getID()))));

    return list(criteria);
}

From source file:org.dspace.content.dao.impl.BitstreamFormatDAOImpl.java

License:BSD License

@Override
public List<BitstreamFormat> findNonInternal(Context context) throws SQLException {
    Criteria criteria = createCriteria(context, BitstreamFormat.class);
    criteria.add(Restrictions.and(Restrictions.eq("internal", false),
            Restrictions.not(Restrictions.like("shortDescription", "Unknown"))));
    criteria.addOrder(Order.desc("supportLevel")).addOrder(Order.asc("shortDescription"));

    return list(criteria);

}

From source file:org.dspace.content.dao.impl.MetadataFieldDAOImpl.java

License:BSD License

@Override
public MetadataField find(Context context, int metadataFieldId, MetadataSchema metadataSchema, String element,
        String qualifier) throws SQLException {
    Criteria criteria = createCriteria(context, MetadataField.class);
    criteria.add(Restrictions.and(Restrictions.not(Restrictions.eq("id", metadataFieldId)),
            Restrictions.eq("metadataSchema.id", metadataSchema.getSchemaID()),
            Restrictions.eq("element", element), Restrictions.eqOrIsNull("qualifier", qualifier)));
    criteria.setCacheable(true);//from   w  w w  .  java  2  s. com

    return singleResult(criteria);
}