Example usage for org.hibernate Query setParameter

List of usage examples for org.hibernate Query setParameter

Introduction

In this page you can find the example usage for org.hibernate Query setParameter.

Prototype

@SuppressWarnings("unchecked")
Query<R> setParameter(int position, Object val);

Source Link

Document

Bind a positional query parameter using its inferred Type.

Usage

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

/**
 * Find people by name//from  ww  w.j av a  2  s  .  c  o  m
 * 
 * @param givenName The given name to search on
 * @param surname The surname to search on
 * @return The list of people with the name
 */
private List<PersonItem> queryPeopleByName(String givenName, String surname) {
    LOGGER.debug("Given Name: {}, Surname: {}", givenName, surname);
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.enableFilter("attributes");

        Query query = session.createQuery(
                "select pi from PersonItem pi join pi.givenNames gn join pi.surnames sn where lower(gn.attrValue) = :givenName and lower(sn.attrValue) = :surname");
        query.setParameter("givenName", givenName.toLowerCase());
        query.setParameter("surname", surname.toLowerCase());

        @SuppressWarnings("unchecked")
        List<PersonItem> people = query.list();
        if (people != null) {
            LOGGER.debug("Number of people found in first query: {}", people.size());
        } else {
            LOGGER.debug("No people found in first query");
        }

        if (people == null || people.size() == 0) {
            query = session.createQuery(
                    "select pi from PersonItem pi join pi.commonNames cn where lower(cn.attrValue) = :commonName");
            query.setParameter("commonName", givenName.toLowerCase() + " " + surname.toLowerCase());

            people = query.list();
            if (people != null) {
                LOGGER.debug("Number of people found in second query: {}", people.size());
            } else {
                LOGGER.debug("No people found in second query");
            }
        }

        return people;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

/**
 * Find people with the given attributes and attribute values
 * /*from  ww w.  j av a 2s .c o  m*/
 * @param attributes The attribute/value pairs to search on
 * @return A list of people with the given attributes
 */
public List<Person> queryPersonByAttributes(Map<String, String> attributes) {
    List<Person> people = new ArrayList<Person>();
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        List<String> parameters = new ArrayList<String>();

        StringBuilder fromString = new StringBuilder();
        StringBuilder whereString = new StringBuilder();

        fromString.append(" FROM PersonItem pi");
        whereString.append(" WHERE");
        int i = 0;
        for (Entry<String, String> entry : attributes.entrySet()) {
            fromString.append(" LEFT JOIN pi.itemAttributes pia");
            fromString.append(i);
            if (i > 0) {
                whereString.append(" AND");
            }
            whereString.append(" pia");
            whereString.append(i);
            whereString.append(".attrType = ? AND lower(pia");
            whereString.append(i);
            whereString.append(".attrValue) like ?");
            parameters.add(entry.getKey());
            parameters.add(entry.getValue().toLowerCase() + "%");

            i++;
        }
        String queryString = "SELECT pi " + fromString.toString() + " " + whereString.toString();
        LOGGER.debug("Query: {}", queryString);
        LOGGER.debug("Number of parameters: {}", parameters.size());
        Query query = session.createQuery(queryString);
        for (i = 0; i < parameters.size(); i++) {
            query.setParameter(i, parameters.get(i));
        }

        @SuppressWarnings("unchecked")
        List<PersonItem> personItems = query.list();

        Person person = null;
        for (PersonItem personItem : personItems) {
            person = getPerson(personItem, false);
            people.add(person);
        }
    } finally {
        session.close();
    }

    return people;
}

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

/**
 * Save the person's information//from   w w w .  ja  v a2s  .c o  m
 * 
 * @param person The person to save
 * @param userUpdated Indicates whether the information is user updated or not
 * @return The item information for the person
 */
public PersonItem savePerson(Person person, Boolean userUpdated) {
    if (person.getExtId() == null) {
        return null;
    }

    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.enableFilter("attributes");

        Query query = session.createQuery("from PersonItem where extId = :extId");
        query.setParameter("extId", person.getExtId());

        PersonItem item = (PersonItem) query.uniqueResult();
        String title = person.getFullName();

        Date lastModified = new Date();
        ItemTraitParser parser = new ItemTraitParser();
        Item newItem = null;

        try {
            newItem = parser.getItem(person, userUpdated, lastModified);
        } catch (Exception e) {
            LOGGER.error("Exception transforming person to an item", e);
        }

        if (item == null) {
            item = new PersonItem();
            item.setExtId(person.getExtId().toLowerCase());
            item.setTitle(title);
            item = (PersonItem) session.merge(item);
        } else {
            item.setTitle(title);
        }

        updateAttributesFromItem(item, newItem, session, lastModified);

        item = (PersonItem) session.merge(item);
        session.getTransaction().commit();
        return item;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

/**
 * Retrieve basic information about a person e.g. their name
 * //from www . j  av  a  2  s.  c om
 * @param uid The unique id of the person to retrieve information about
 * @return The information about the person
 */
public Person getPerson(String uid) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.enableFilter("attributes");
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("from PersonItem where extId = :extId");
        query.setParameter("extId", uid);

        PersonItem item = (PersonItem) query.uniqueResult();

        Person person = null;
        if (item != null) {
            person = getPerson(item);
        }
        transaction.commit();

        return person;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

/**
 * Retrieve basic information about a person e.g. their name
 * // ww  w.  j a  va 2  s .c  o  m
 * @param uid The unique id of the person to retrieve information about
 * @param extraInfo Indicates whether to retrieve the type, institution, country and organisational unit about the person
 * @return Information about the given person
 */
public Person getBasicPerson(String uid, boolean extraInfo) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.enableFilter("attributes");
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery(
                "select pi from PersonItem pi join fetch pi.itemAttributes where pi.extId = :extId");
        query.setParameter("extId", uid);

        PersonItem item = (PersonItem) query.uniqueResult();
        Person person = null;
        if (item != null) {
            person = getBasicPerson(item, extraInfo);
        }
        transaction.commit();

        return person;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.people.PersonService.java

License:Open Source License

public List<Person> getCurrentAriesPeople() {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {//from   w  w  w  .j  ava2 s.c  o  m
        //TODO limit this by current people?
        Query query = session
                .createQuery("FROM PersonItem item WHERE EXISTS (SELECT 1 FROM item.itemAttributes ia "
                        + "WHERE ia.attrType = :ariesAttrType) "
                        + "AND EXISTS (SELECT 1 FROM item.itemAttributes ia "
                        + "WHERE ia.attrType = :uidAttrType) "
                        + "AND EXISTS (SELECT 1 FROM item.itemAttributes ia "
                        + "WHERE ia.attrType = :activeAttr " + "AND ia.attrValue = :activeValue) ");
        query.setParameter("ariesAttrType", StoreAttributes.ARIES_ID);
        query.setParameter("uidAttrType", StoreAttributes.UNIVERSITY_ID);
        query.setParameter("activeAttr", StoreAttributes.ACTIVE);
        query.setParameter("activeValue", Boolean.TRUE.toString());
        @SuppressWarnings("unchecked")
        List<PersonItem> peopleItems = query.list();
        LOGGER.info("Number of people: {}", peopleItems.size());
        List<Person> people = getPeople(peopleItems.subList(0, Math.min(peopleItems.size(), 100)), true);
        //List<Person> people = getPeople(peopleItems, true);
        return people;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.publication.PublicationService.java

License:Open Source License

/**
 * Save the publication// w  ww  .j  a va  2  s.  c o m
 * 
 * @param publication The publication to save
 * @param userUpdated Indicates whether the update is user updated
 * @return The publication item
 */
public PublicationItem savePublication(Publication publication, Boolean userUpdated) {
    if (publication.getTitle() == null || publication.getTitle().trim().length() == 0) {
        return null;
    }

    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        session.enableFilter("attributes");

        //note this may need to be updated if we retrieve publications from other systems without an aries id
        Query query = session.createQuery(
                "SELECT pi FROM PublicationItem as pi inner join pi.itemAttributes as pia WHERE pia.attrType = :attrType and pia.attrValue = :attrValue");
        query.setParameter("attrType", StoreAttributes.ARIES_ID);
        query.setParameter("attrValue", publication.getAriesId());

        PublicationItem item = (PublicationItem) query.uniqueResult();

        Date lastModified = new Date();
        ItemTraitParser parser = new ItemTraitParser();
        Item newItem = null;
        try {
            newItem = parser.getItem(publication, userUpdated, lastModified);
        } catch (Exception e) {
            LOGGER.error("Exception transforming grant to an item", e);
        }

        if (item == null) {
            item = new PublicationItem();
            Query idQuery = session.createSQLQuery("SELECT nextval('publication_seq')");
            BigInteger id = (BigInteger) idQuery.uniqueResult();
            item.setExtId("p" + id.toString());
            item.setTitle(publication.getTitle());
            item = (PublicationItem) session.merge(item);
        } else if (publication.getTitle() != null && publication.getTitle().trim().length() > 0) {
            item.setTitle(publication.getTitle());
        }
        updateAttributesFromItem(item, newItem, session, lastModified);

        //TODO remove people who are no longer related
        Item personItem = null;
        ItemRelation itemRelation = null;
        ItemRelationId id = null;
        List<Item> peopleItems = new ArrayList<Item>();
        for (Person person : publication.getAuthors()) {
            personItem = personService_.getPersonItem(person.getUid());
            if (personItem != null) {
                peopleItems.add(personItem);
            } else {
                LOGGER.error("No person found to add relation for id: {}", person.getUid());
            }
        }
        boolean hasPerson = false;
        for (Item item2 : peopleItems) {
            for (ItemRelation relation : item.getItemRelationsForIid()) {
                if (relation.getId().getRelatedIid().equals(item2.getIid())) {
                    hasPerson = true;
                    break;
                }
            }
            if (!hasPerson) {
                itemRelation = new ItemRelation();
                id = new ItemRelationId(item.getIid(), StoreProperties.getProperty("publication.author.type"),
                        item2.getIid());
                itemRelation.setId(id);
                item.getItemRelationsForIid().add(itemRelation);
            }
            hasPerson = false;
        }

        item = (PublicationItem) session.merge(item);

        session.getTransaction().commit();

        return item;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.publication.PublicationService.java

License:Open Source License

/**
 * Tries to find an aries record within the database.  If it does not find it it searches the aries database and saves it.
 * //from  www .  j  a  v a  2 s  .com
 * @param ariesId The id of the aries record to return an item for
 * @return The publication item for the given aries id
 */
public PublicationItem getPublicationItem(String ariesId) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.enableFilter("attributes");
        session.beginTransaction();

        Query query = session.createQuery(
                "SELECT pi FROM PublicationItem as pi inner join pi.itemAttributes as pia WHERE pia.attrType = :attrType and pia.attrValue = :attrValue");
        query.setParameter("attrType", StoreAttributes.ARIES_ID);
        query.setParameter("attrValue", ariesId);

        PublicationItem item = (PublicationItem) query.uniqueResult();
        if (item != null) {
            return item;
        }

        Publication publication = fetchPublication(ariesId);
        item = savePublication(publication);

        session.getTransaction().commit();

        return item;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.publication.PublicationService.java

License:Open Source License

/**
 * Searches for the people that match the publication with an author that has the provided given and surnames
 * //from w  w w .  java 2  s.  co  m
 * @param iid The item id of the publication
 * @param givenName The given name
 * @param surname The surname
 * @return The list of people that match
 */
public List<PersonItem> searchPublicationPerson(Long iid, String givenName, String surname) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.enableFilter("attributes");

        Query query = session.createQuery(
                "SELECT pi FROM ItemRelation ir join ir.itemByRelatedIid pi join pi.givenNames gn join pi.surnames sn WHERE ir.id.iid = :iid AND pi.extSystem = :extSystem AND lower(gn.attrValue) like :givenName and lower(sn.attrValue) = :surname");
        query.setParameter("iid", iid);
        query.setParameter("extSystem", "PERSON");
        query.setParameter("givenName", givenName.toLowerCase() + "%");
        query.setParameter("surname", surname.toLowerCase());

        @SuppressWarnings("unchecked")
        List<PersonItem> people = query.list();
        return people;
    } finally {
        session.close();
    }
}

From source file:au.edu.anu.metadatastores.store.publication.PublicationService.java

License:Open Source License

/**
 * Get the publication by the aries id// w ww  .j av a  2  s .  co  m
 * 
 * @param ariesId The aries id to get publications for
 * @return The publication
 */
public Publication getPublicationByAriesId(String ariesId) {
    Session session = StoreHibernateUtil.getSessionFactory().openSession();
    try {
        session.enableFilter("attributes");
        session.beginTransaction();

        Query query = session.createQuery(
                "SELECT pi FROM PublicationItem as pi inner join pi.itemAttributes as pia WHERE pia.attrType = :attrType and pia.attrValue = :attrValue");
        query.setParameter("attrType", StoreAttributes.ARIES_ID);
        query.setParameter("attrValue", ariesId);

        PublicationItem item = (PublicationItem) query.uniqueResult();

        Publication publication = null;

        if (item != null) {
            publication = getPublication(item);
        }

        session.getTransaction().commit();

        return publication;
    } finally {
        session.close();
    }
}