List of usage examples for org.hibernate Criteria setFetchMode
public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException;
From source file:org.archiviststoolkit.mydomain.DomainAccessObjectImpl.java
License:Open Source License
/** * Find an instance by its identifier.// ww w . j a v a2s .c o m * * @param identifier the identifier we are looking for * @return the domain object with the required identifier * @throws LookupException fails if we cannot execute the lookup */ public DomainObject findByPrimaryKeyCommon(final Long identifier, Session session) throws LookupException { DomainObject domainObject; try { // try { if (getPersistentClass() == Names.class) { Criteria criteria = session.createCriteria(Names.class); criteria.setFetchMode("contactNotes", FetchMode.JOIN); criteria.setFetchMode("nonPreferredNames", FetchMode.JOIN); criteria.setFetchMode("archDescriptionNames", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else if (getPersistentClass() == Accessions.class) { Criteria criteria = session.createCriteria(Accessions.class); criteria.setFetchMode("names", FetchMode.JOIN); criteria.setFetchMode("repeatingData", FetchMode.JOIN); criteria.setFetchMode("resources", FetchMode.JOIN); criteria.setFetchMode("subjects", FetchMode.JOIN); criteria.setFetchMode("locations", FetchMode.JOIN); criteria.setFetchMode("deaccessions", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else if (getPersistentClass() == Subjects.class) { Criteria criteria = session.createCriteria(Subjects.class); criteria.setFetchMode("archDescriptionSubjects", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else if (getPersistentClass() == Resources.class) { Criteria criteria = session.createCriteria(Resources.class); criteria.setFetchMode("names", FetchMode.JOIN); criteria.setFetchMode("accessions", FetchMode.JOIN); criteria.setFetchMode("subjects", FetchMode.JOIN); // criteria.setFetchMode("repeatingData", FetchMode.JOIN); // criteria.setFetchMode("instances", FetchMode.JOIN); // criteria.setFetchMode("resourcesComponents", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else if (getPersistentClass() == ResourcesComponents.class) { Criteria criteria = session.createCriteria(ResourcesComponents.class); criteria.setFetchMode("names", FetchMode.JOIN); criteria.setFetchMode("instances", FetchMode.JOIN); criteria.setFetchMode("subjects", FetchMode.JOIN); criteria.setFetchMode("repeatingData", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else if (getPersistentClass() == Locations.class) { Criteria criteria = session.createCriteria(Locations.class); criteria.setFetchMode("repository", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else if (getPersistentClass() == DigitalObjects.class) { Criteria criteria = session.createCriteria(DigitalObjects.class); // criteria.setFetchMode("names", FetchMode.JOIN); // criteria.setFetchMode("repeatingData", FetchMode.JOIN); // criteria.setFetchMode("subjects", FetchMode.JOIN); // criteria.setFetchMode("fileVersions", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); domainObject = (DomainObject) criteria.uniqueResult(); } else { domainObject = (DomainObject) session.load(getPersistentClass(), identifier); } // } catch (ObjectNotFoundException objectNotFoundException) { // new ErrorDialog("", StringHelper.getStackTrace(e)).showDialog(); // domainObject = null; // logger.log(Level.INFO, "Object could not be found by key " + identifier); // } session.flush(); session.connection().commit(); } catch (ObjectNotFoundException objectNotFoundException) { throw new LookupException("failed to findbyprimarykey: " + objectNotFoundException.toString(), objectNotFoundException); } catch (HibernateException hibernateException) { throw new LookupException("failed to findbyprimarykey: " + hibernateException.toString(), hibernateException); } catch (SQLException sqlException) { throw new LookupException("failed to findbyprimarykey: " + sqlException.toString(), sqlException); } return (domainObject); }
From source file:org.archiviststoolkit.plugin.dbdialog.RemoteDBConnectDialogLight.java
/** * Method to return the resource in a long session * * @param identifier/*from www. j a va 2 s. c o m*/ * @return */ public Resources getResource(Long identifier) { Transaction tx = null; Resources resource = null; try { tx = session.beginTransaction(); Criteria criteria = session.createCriteria(Resources.class); criteria.setFetchMode("names", FetchMode.JOIN); criteria.setFetchMode("accessions", FetchMode.JOIN); criteria.setFetchMode("subjects", FetchMode.JOIN); criteria.add(Restrictions.idEq(identifier)); resource = (Resources) criteria.uniqueResult(); session.setReadOnly(resource, true); tx.commit(); } catch (RuntimeException ex) { try { tx.rollback(); } catch (HibernateException e) { e.printStackTrace(); } } return resource; }
From source file:org.atemsource.atem.impl.hibernate.service.HibernateDao.java
License:Apache License
public Result getEntities(Class entityClass, int startIndex, int count, Sorting sorting, List<String> associationPaths) { try {// ww w . j av a2 s. c om Criteria query = getSession().createCriteria(entityClass, "entity"); if (count > 0) { query.setMaxResults(count); } if (startIndex >= 0) { query.setFirstResult(startIndex); } for (String associationPath : associationPaths) { query.setFetchMode(associationPath, FetchMode.SELECT); } List entities = query.list(); Integer totalCount = entities.size(); if (count <= 0) { totalCount = ((Number) getSession().createQuery("select count(*) from " + entityClass.getName()) .uniqueResult()).intValue(); } return new Result(entities, totalCount); } catch (Exception e) { throw new TechnicalException("cannot get entities of type " + entityClass.getName(), e); } }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java
License:Apache License
/** * Populates criteria arguments for the given target class and arguments map * * @param grailsApplication the GrailsApplication instance * @param targetClass The target class/* ww w . j av a 2 s. co m*/ * @param c The criteria instance * @param argMap The arguments map * */ @SuppressWarnings("rawtypes") public static void populateArgumentsForCriteria(GrailsApplication grailsApplication, Class<?> targetClass, Criteria c, Map argMap) { Integer maxParam = null; Integer offsetParam = null; SimpleTypeConverter converter = new SimpleTypeConverter(); if (argMap.containsKey(ARGUMENT_MAX)) { maxParam = converter.convertIfNecessary(argMap.get(ARGUMENT_MAX), Integer.class); } if (argMap.containsKey(ARGUMENT_OFFSET)) { offsetParam = converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET), Integer.class); } if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) { c.setFetchSize(converter.convertIfNecessary(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class)); } if (argMap.containsKey(ARGUMENT_TIMEOUT)) { c.setTimeout(converter.convertIfNecessary(argMap.get(ARGUMENT_TIMEOUT), Integer.class)); } if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) { c.setFlushMode(converter.convertIfNecessary(argMap.get(ARGUMENT_FLUSH_MODE), FlushMode.class)); } if (argMap.containsKey(ARGUMENT_READ_ONLY)) { c.setReadOnly(GrailsClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap)); } String orderParam = (String) argMap.get(ARGUMENT_ORDER); Object fetchObj = argMap.get(ARGUMENT_FETCH); if (fetchObj instanceof Map) { Map fetch = (Map) fetchObj; for (Object o : fetch.keySet()) { String associationName = (String) o; c.setFetchMode(associationName, getFetchMode(fetch.get(associationName))); } } final String sort = (String) argMap.get(ARGUMENT_SORT); final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC; final int max = maxParam == null ? -1 : maxParam; final int offset = offsetParam == null ? -1 : offsetParam; if (max > -1) { c.setMaxResults(max); } if (offset > -1) { c.setFirstResult(offset); } if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap)) { c.setCacheable(true); } if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) { c.setLockMode(LockMode.PESSIMISTIC_WRITE); } else { if (argMap.get(ARGUMENT_CACHE) == null) { cacheCriteriaByMapping(targetClass, c); } } if (sort != null) { boolean ignoreCase = true; Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE); if (caseArg instanceof Boolean) { ignoreCase = (Boolean) caseArg; } addOrderPossiblyNested(grailsApplication, c, targetClass, sort, order, ignoreCase); } else { Mapping m = GrailsDomainBinder.getMapping(targetClass); if (m != null && !StringUtils.isBlank(m.getSort())) { addOrderPossiblyNested(grailsApplication, c, targetClass, m.getSort(), m.getOrder(), true); } } }
From source file:org.ednovo.gooru.infrastructure.persistence.hibernate.content.ContentRepositoryHibernate.java
License:Open Source License
@SuppressWarnings({ "unchecked", "deprecation" }) @Override/*from www . j a v a2 s . c om*/ public Content findContentByGooruId(String gooruContentId, boolean fetchUser) { if (!fetchUser) { List<Content> cc = getSession().createQuery( "SELECT c FROM Content c WHERE c.gooruOid = ? AND " + generateAuthQueryWithDataNew("c.")) .setString(0, gooruContentId).list(); return cc.size() == 0 ? null : cc.get(0); } else { Criteria crit = getSession().createCriteria(Content.class); crit.setFetchMode("user", FetchMode.EAGER).setFetchMode("userPermSet", FetchMode.JOIN) .add(Restrictions.eq("gooruOid", gooruContentId)); Content content = (Content) crit.uniqueResult(); return content; } }
From source file:org.emonocot.persistence.dao.hibernate.DaoImpl.java
License:Open Source License
/** * * @param criteria//from www . j a va2 s .co m * Set a Criteria instance * @param fetch * Set the name of the fetch profile * @return true if the criteria have been set, false otherwise */ protected boolean enableProfilePreQuery(final Criteria criteria, final String fetch) { boolean setCriteria = false; if (fetch != null) { for (Fetch f : getProfile(fetch)) { if (f.getMode().equals(FetchMode.JOIN)) { criteria.setFetchMode(f.getAssociation(), f.getMode()); setCriteria = true; } } } return setCriteria; }
From source file:org.esn.esobase.data.DBService.java
@Transactional public SysAccount getAccount(String login) { SysAccount result = null;// w w w. ja va 2s . c o m Session session = (Session) em.getDelegate(); Criteria crit = session.createCriteria(SysAccount.class); crit.add(Restrictions.eq("login", login)); crit.setFetchMode("roles", FetchMode.JOIN); crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); result = (SysAccount) crit.uniqueResult(); return result; }
From source file:org.esn.esobase.data.DBService.java
@Transactional public BeanItemContainer<Npc> getNpcs(BeanItemContainer<Npc> container, TRANSLATE_STATUS translateStatus, SysAccount translator, boolean noTranslations) { container.removeAllItems();/*from w w w .ja va 2 s . co m*/ Session session = (Session) em.getDelegate(); Criteria crit = session.createCriteria(Npc.class); crit.setFetchMode("location", FetchMode.JOIN); if (translateStatus != null && translator != null) { Query q = em.createNativeQuery( "select npc_id from (select t.npc_id from translatedtext tt join topic t on tt.npctopic_id=t.id where tt.status=:translateStatus and tt.author_id=:authorId\n" + "union all select t.npc_id from translatedtext tt join topic t on tt.playertopic_id=t.id where tt.status=:translateStatus and tt.author_id=:authorId\n" + "union all select t.npc_id from translatedtext tt join greeting t on tt.greeting_id=t.id where tt.status=:translateStatus and tt.author_id=:authorId\n" + "union all select t.npc_id from translatedtext tt join subtitle t on tt.subtitle_id=t.id where tt.status=:translateStatus and tt.author_id=:authorId) as rr group by npc_id"); q.setParameter("authorId", translator.getId()); q.setParameter("translateStatus", translateStatus.name()); List<BigInteger> resultList = q.getResultList(); List<Long> longResultList = new ArrayList(); for (BigInteger id : resultList) { longResultList.add(id.longValue()); } if (longResultList.isEmpty()) { longResultList.add(0L); } crit.add(Restrictions.in("id", longResultList)); } else if (translateStatus != null) { Query q = em.createNativeQuery( "select npc_id from (select t.npc_id from translatedtext tt join topic t on tt.npctopic_id=t.id where tt.status=:translateStatus\n" + "union all select t.npc_id from translatedtext tt join topic t on tt.playertopic_id=t.id where tt.status=:translateStatus\n" + "union all select t.npc_id from translatedtext tt join greeting t on tt.greeting_id=t.id where tt.status=:translateStatus\n" + "union all select t.npc_id from translatedtext tt join subtitle t on tt.subtitle_id=t.id where tt.status=:translateStatus) as rr group by npc_id"); q.setParameter("translateStatus", translateStatus.name()); List<BigInteger> resultList = q.getResultList(); List<Long> longResultList = new ArrayList(); for (BigInteger id : resultList) { longResultList.add(id.longValue()); } if (longResultList.isEmpty()) { longResultList.add(0L); } crit.add(Restrictions.in("id", longResultList)); } else if (translator != null) { Query q = em.createNativeQuery( "select npc_id from (select t.npc_id from translatedtext tt join topic t on tt.npctopic_id=t.id where tt.author_id=:authorId\n" + "union all select t.npc_id from translatedtext tt join topic t on tt.playertopic_id=t.id where tt.author_id=:authorId\n" + "union all select t.npc_id from translatedtext tt join greeting t on tt.greeting_id=t.id where tt.author_id=:authorId\n" + "union all select t.npc_id from translatedtext tt join subtitle t on tt.subtitle_id=t.id where tt.author_id=:authorId) as rr group by npc_id"); q.setParameter("authorId", translator.getId()); List<BigInteger> resultList = q.getResultList(); List<Long> longResultList = new ArrayList(); for (BigInteger id : resultList) { longResultList.add(id.longValue()); } if (longResultList.isEmpty()) { longResultList.add(0L); } crit.add(Restrictions.in("id", longResultList)); } if (noTranslations) { crit.add(Restrictions.lt("progress", BigDecimal.ONE)); } crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<Npc> list = crit.list(); container.addAll(list); return container; }
From source file:org.fornax.cartridges.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByConditionAccessImpl.java
License:Apache License
private void addFetchStrategy(Criteria criteria) { for (ConditionalCriteria crit : cndCriterias) { if (Operator.FetchEager.equals(crit.getOperator())) { criteria.setFetchMode(crit.getPropertyFullName(), FetchMode.JOIN); } else if (Operator.FetchLazy.equals(crit.getOperator())) { criteria.setFetchMode(crit.getPropertyFullName(), FetchMode.SELECT); }//from w w w . java 2 s.co m } }
From source file:org.fornax.cartridges.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByCriteriaAccessImpl.java
License:Apache License
/** * Add the fetch modes to the criteria. Can be overridden * to build more advanced criterias./* ww w.j a v a 2 s .c o m*/ */ protected void addFetch(Criteria criteria) { for (String associationPath : fetchAssociations) { criteria.setFetchMode(associationPath, getFetchMode(associationPath)); } }