Example usage for org.springframework.orm.hibernate5 HibernateCallback HibernateCallback

List of usage examples for org.springframework.orm.hibernate5 HibernateCallback HibernateCallback

Introduction

In this page you can find the example usage for org.springframework.orm.hibernate5 HibernateCallback HibernateCallback.

Prototype

HibernateCallback

Source Link

Usage

From source file:org.encuestame.persistence.dao.imp.AccountDaoImp.java

public List<UserAccount> getPublicProfiles(final String keyword, final Integer maxResults,
        final Integer startOn) {
    final List<UserAccount> searchResult = (List<UserAccount>) getHibernateTemplate()
            .execute(new HibernateCallback() {
                public Object doInHibernate(org.hibernate.Session session) {
                    List<UserAccount> searchResult = new ArrayList<UserAccount>();
                    long start = System.currentTimeMillis();
                    final Criteria criteria = session.createCriteria(UserAccount.class);
                    //only shared profiles.
                    criteria.add(Restrictions.eq("sharedProfile", Boolean.TRUE));
                    // limit results
                    if (maxResults != null) {
                        criteria.setMaxResults(maxResults.intValue());
                    }//from www. j a  va2  s. c  o m
                    // start on page x
                    if (startOn != null) {
                        criteria.setFirstResult(startOn.intValue());
                    }
                    searchResult = (List<UserAccount>) fetchMultiFieldQueryParserFullText(keyword,
                            new String[] { "completeName, username" }, UserAccount.class, criteria,
                            new SimpleAnalyzer());
                    final List listAllSearch = new LinkedList();
                    listAllSearch.addAll(searchResult);

                    // Fetch result by phrase
                    final List<UserAccount> phraseFullTestResult = (List<UserAccount>) fetchPhraseFullText(
                            keyword, "completeName", UserAccount.class, criteria, new SimpleAnalyzer());
                    log.debug("phraseFullTestResult:{" + phraseFullTestResult.size());
                    listAllSearch.addAll(phraseFullTestResult);
                    // Fetch result by wildcard
                    final List<UserAccount> wildcardFullTextResult = (List<UserAccount>) fetchWildcardFullText(
                            keyword, "completeName", UserAccount.class, criteria, new SimpleAnalyzer());
                    log.debug("wildcardFullTextResult:{" + wildcardFullTextResult.size());
                    listAllSearch.addAll(wildcardFullTextResult);
                    // Fetch result by prefix
                    final List<UserAccount> prefixQueryFullTextResuslts = (List<UserAccount>) fetchPrefixQueryFullText(
                            keyword, "completeName", UserAccount.class, criteria, new SimpleAnalyzer());
                    log.debug("prefixQueryFullTextResuslts:{" + prefixQueryFullTextResuslts.size());
                    listAllSearch.addAll(prefixQueryFullTextResuslts);
                    // Fetch fuzzy results
                    final List<UserAccount> fuzzyQueryFullTextResults = (List<UserAccount>) fetchFuzzyQueryFullText(
                            keyword, "completeName", UserAccount.class, criteria, new SimpleAnalyzer(),
                            SIMILARITY_VALUE);
                    log.debug("fuzzyQueryFullTextResults: {" + fuzzyQueryFullTextResults.size());
                    listAllSearch.addAll(fuzzyQueryFullTextResults);

                    log.debug("listAllSearch size:{" + listAllSearch.size());

                    // removing duplcates
                    final ListOrderedSet totalResultsWithoutDuplicates = ListOrderedSet
                            .decorate(new LinkedList());
                    totalResultsWithoutDuplicates.addAll(listAllSearch);

                    /*
                     * Limit results if is enabled.
                     */
                    List<UserAccount> totalList = totalResultsWithoutDuplicates.asList();
                    if (maxResults != null && startOn != null) {
                        log.debug("split to " + maxResults + " starting on " + startOn + " to list with size "
                                + totalList.size());
                        totalList = totalList.size() > maxResults ? totalList.subList(startOn, maxResults)
                                : totalList;
                    }
                    long end = System.currentTimeMillis();
                    log.debug("UserAccount{ totalResultsWithoutDuplicates:{" + totalList.size()
                            + " items with search time:" + (end - start) + " milliseconds");
                    return totalList;
                }
            });
    return searchResult;
}

From source file:org.encuestame.persistence.dao.imp.FrontEndDao.java

public List<Hit> getHitsByIpAndType(final String ipAddress, final Long id, final TypeSearchResult searchHitby) {
    log.debug("searching item hits by ipAddress ---> " + ipAddress);
    @SuppressWarnings({ "unchecked", "rawtypes" })
    List<Hit> searchResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(org.hibernate.Session session) {
            List<Hit> searchResult = new ArrayList<Hit>();
            final Criteria criteria = session.createCriteria(Hit.class);
            if (searchHitby.equals(TypeSearchResult.TWEETPOLL)) {
                criteria.createAlias("tweetPoll", "tweetPoll");
                criteria.add(Restrictions.eq("tweetPoll.tweetPollId", id));
            } else if (searchHitby.equals(TypeSearchResult.POLL)) {
                criteria.createAlias("poll", "poll");
                criteria.add(Restrictions.eq("poll.pollId", id));
            } else if (searchHitby.equals(TypeSearchResult.SURVEY)) {
                criteria.createAlias("survey", "survey");
                criteria.add(Restrictions.eq("survey.sid", id));
            } else if (searchHitby.equals(TypeSearchResult.HASHTAG)) {
                criteria.createAlias("hashTag", "hashTag");
                criteria.add(Restrictions.eq("hashTag.hashTagId", id));
            } else {
                log.error(" Search hit result type undefined " + searchHitby);
            }//from  ww w. j a  v  a  2  s . c  o m
            //define the type of hit.
            criteria.add(Restrictions.eq("hitCategory", HitCategory.VISIT));
            searchResult = (List<Hit>) fetchPhraseFullText(ipAddress, "ipAddress", Hit.class, criteria,
                    new SimpleAnalyzer());
            log.debug("total hits results ---> " + searchResult.size());
            return searchResult;
        }
    });
    return searchResult;
}

From source file:org.encuestame.persistence.dao.imp.FrontEndDao.java

public List<AccessRate> getAccessRatebyItem(final String ipAddress, final Long itemId,
        final TypeSearchResult searchbyType) {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    List<AccessRate> searchResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(org.hibernate.Session session) {
            List<AccessRate> searchResult = new ArrayList<AccessRate>();
            final Criteria criteria = session.createCriteria(AccessRate.class);
            if (searchbyType.equals(TypeSearchResult.TWEETPOLL)) {
                criteria.createAlias("tweetPoll", "tweetPoll");
                criteria.add(Restrictions.eq("tweetPoll.tweetPollId", itemId));
            } else if (searchbyType.equals(TypeSearchResult.SURVEY)) {
                criteria.createAlias("survey", "survey");
                criteria.add(Restrictions.eq("survey.sid", itemId));
            } else if (searchbyType.equals(TypeSearchResult.POLL)) {
                criteria.createAlias("poll", "poll");
                criteria.add(Restrictions.eq("poll.pollId", itemId));
            } else {
                log.error(" Search access rate result type undefined " + searchbyType);
            }//from   w ww .  ja  v a 2 s  . c  om
            searchResult = (List<AccessRate>) fetchPhraseFullText(ipAddress, "ipAddress", AccessRate.class,
                    criteria, new SimpleAnalyzer());
            return searchResult;
        }
    });
    return searchResult;
}

From source file:org.encuestame.persistence.dao.imp.HashTagDao.java

@SuppressWarnings("unchecked")
public List<HashTag> getListHashTagsByKeyword(final String keyword, final Integer maxResults,
        final Long[] excludes) {
    log.info("keyword " + keyword);
    List<HashTag> searchResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
        @SuppressWarnings("deprecation")
        public Object doInHibernate(org.hibernate.Session session) {
            final Criteria criteria = session.createCriteria(HashTag.class);
            // limit results
            if (maxResults != null) {
                criteria.setMaxResults(maxResults.intValue());
            }//w ww  . ja v  a  2s .  co m
            if (excludes != null && excludes.length > 0) {
                for (int i = 0; i < excludes.length; i++) {
                    log.debug("excluding hashtag... " + excludes[i]);
                    criteria.add(Restrictions.ne("hashTagId", excludes[i]));
                }
            }
            final QueryBuilder<HashTag> query = new QueryBuilder<>(getSessionFactory());
            List<HashTag> results = query.build(criteria, keyword, maxResults, 0, new String[] { "hashTag" },
                    "hashTag", HashTag.class);
            return results;
        }
    });
    return searchResult;
}

From source file:org.encuestame.persistence.dao.imp.PollDao.java

@SuppressWarnings("unchecked")
public List<Poll> getPollsByQuestionKeyword(final String keyword, final UserAccount userAcc,
        final Integer maxResults, final Integer startOn) {
    log.debug("keyword " + keyword);

    @SuppressWarnings("rawtypes")
    final List<Poll> searchResult = (List) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(org.hibernate.Session session) {
            final Criteria criteria = session.createCriteria(Poll.class);
            //filter by account und .
            if (userAcc != null) {
                criteria.add(Restrictions.eq("editorOwner", userAcc));
            } else {
                // Retrieve without hidden polls
                criteria.add(Restrictions.eq("isHidden", Boolean.FALSE));
            }// www.  j  a va2  s .  com
            //limit results
            if (maxResults != null) {
                criteria.setMaxResults(maxResults.intValue());
            }
            //start on page x
            if (startOn != null) {
                criteria.setFirstResult(startOn.intValue());
            }
            final String defaultField = "question.question";
            final String[] fields = new String[] { defaultField };
            final QueryBuilder<Poll> query = new QueryBuilder<>(getSessionFactory());
            List<Poll> results = query.build(criteria, keyword, maxResults, 0, fields, "question", Poll.class);
            return results;
        }
    });
    return (List<Poll>) searchResult;
}

From source file:org.encuestame.persistence.dao.imp.QuestionDaoImp.java

@SuppressWarnings("unchecked")
public final List<Question> retrieveIndexQuestionsByKeyword(final String keyword, final Long userId,
        final String[] fields, final Integer maxResults, final Integer startOn) {
    log.debug("keyword " + keyword);
    log.debug("userId " + userId);
    log.debug("fields " + fields);
    @SuppressWarnings("rawtypes")
    final List<Question> searchResult = (List<Question>) getHibernateTemplate()
            .execute(new HibernateCallback() {
                public Object doInHibernate(org.hibernate.Session session) {
                    final Criteria criteria = session.createCriteria(Question.class);
                    //filter by account.
                    if (userId != null) {
                        criteria.createAlias("accountQuestion", "accountQuestion");
                        criteria.add(Restrictions.eq("accountQuestion.uid", userId));
                    }/*from   w  ww.  j  a v a2 s  .  c  o m*/
                    //else {
                    //if user id is missing, the question should be shared to be listed.
                    //criteria.add(Restrictions.eq("sharedQuestion", Boolean.TRUE));
                    //}
                    //limit results
                    if (maxResults != null) {
                        criteria.setMaxResults(maxResults.intValue());
                    }
                    //start on page x
                    if (startOn != null) {
                        criteria.setFirstResult(startOn.intValue());
                    }
                    final QueryBuilder<Question> query = new QueryBuilder<>(getSessionFactory());
                    List<Question> results = query.build(criteria, keyword, maxResults, 0,
                            new String[] { "question" }, "question", Question.class);
                    return results;
                }
            });
    return (List<Question>) searchResult;
}

From source file:org.projectforge.framework.persistence.api.BaseDao.java

public List<DisplayHistoryEntry> internalGetDisplayHistoryEntries(final BaseDO<?> obj) {
    accessChecker.checkRestrictedUser();
    final List<DisplayHistoryEntry> result = hibernateTemplate
            .execute(new HibernateCallback<List<DisplayHistoryEntry>>() {
                @SuppressWarnings("rawtypes")
                @Override// w w  w .  j  a va  2s. c  om
                public List<DisplayHistoryEntry> doInHibernate(Session session) throws HibernateException {
                    final HistoryEntry[] entries = internalGetHistoryEntries(obj);
                    if (entries == null) {
                        return null;
                    }
                    return convertAll(entries, session);
                }
            });
    return result;
}

From source file:org.projectforge.framework.persistence.history.HibernateSearchReindexer.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void reindex(final Class<?> clazz, final ReindexSettings settings, final StringBuffer buf) {
    // PF-378: Performance of run of full re-indexing the data-base is very slow for large data-bases
    // Single transactions needed, otherwise the full run will be very slow for large data-bases.
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        // The call-back is needed, otherwise a lot of transactions are left open until last run is completed:
        @Override//from   w w w .j  a v  a  2s. c o  m
        public Object doInTransaction(final TransactionStatus status) {
            try {
                hibernate.execute(new HibernateCallback() {
                    @Override
                    public Object doInHibernate(final Session session) throws HibernateException {
                        databaseDao.reindex(clazz, settings, buf);
                        status.setRollbackOnly();
                        return null;
                    }
                });
            } catch (final Exception ex) {
                buf.append(" (an error occured, see log file for further information.), ");
                log.error("While rebuilding data-base-search-index for '" + clazz.getName() + "': "
                        + ex.getMessage(), ex);
            }
            return null;
        }
    });
}

From source file:org.projectforge.framework.persistence.xstream.HibernateXmlConverter.java

/**
 * Schreibt alle Objekte der Datenbank in den angegebenen Writer.<br/>
 * <b>Warnung!</b> Bei der Serialisierung von Collections wird derzeit nur {@link java.util.Set} sauber untersttzt.
 * /*  w  ww. ja v  a2s .  c  o m*/
 * @param writer Ziel fr die XML-Datei.
 * @param includeHistory bei false werden die History Eintrge nicht geschrieben
 * @param preserveIds If true, the object ids will be preserved, otherwise new ids will be assigned through xstream.
 */
public void dumpDatabaseToXml(final Writer writer, final boolean includeHistory, final boolean preserveIds) {
    final TransactionTemplate tx = new TransactionTemplate(
            new HibernateTransactionManager(hibernate.getSessionFactory()));
    tx.execute(new TransactionCallback() {
        @Override
        public Object doInTransaction(final TransactionStatus status) {
            hibernate.execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(final Session session) throws HibernateException {
                    writeObjects(writer, includeHistory, session, preserveIds);
                    status.setRollbackOnly();
                    return null;
                }
            });
            return null;
        }
    });
}