org.hibernate.FetchMode Java Examples

The following examples show how to use org.hibernate.FetchMode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public WallItemComment getWallItemComment(final long wallItemCommentId) {

	final HibernateCallback<List<WallItemComment>> hcb = session -> session.createCriteria(WallItemComment.class)
               .add(Restrictions.eq(ID, wallItemCommentId))
               .setFetchMode("wallItem", FetchMode.JOIN)
               .list();

	final List<WallItemComment> comments = getHibernateTemplate().execute(hcb);

	if (comments.size() > 0) {
	    return comments.get(0);
	} else {
		return null;
	}
}
 
Example #2
Source File: Select.java    From HibernateDemos with The Unlicense 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<User> getUsers() {
	final Session session = openSession();
	session.getTransaction().begin();

	final List<User> users = session
			.createCriteria( User.class )
			.setFetchMode( "communityMemberships", FetchMode.SELECT ) // not necessary (default)
			.list();
	
	// init
	users.get( 0 ).getCommunityMemberships().size();
	users.get( 1 ).getCommunityMemberships().size();

	session.getTransaction().commit();
	return users;
}
 
Example #3
Source File: Join.java    From hibernate-demos with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		final Session session = openSession();
		session.getTransaction().begin();

		// Note: Can use multiple associations with JOIN fetch mode if they are *not*, but results in a cartesian product!
		
		final List<User> users = session
				.createCriteria( User.class )
				.setFetchMode( "projectsSubmitted", FetchMode.JOIN )
//				.setFetchMode( "projectsOrganized", FetchMode.JOIN )
				.list();

		session.getTransaction().commit();
		return users;
	}
 
Example #4
Source File: SyllabusManagerImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public Set getSyllabusAttachmentsForSyllabusData(final SyllabusData syllabusData)
{
  if (syllabusData == null)
  {
    throw new IllegalArgumentException("Null Argument");
  }
  else
  {                 
    HibernateCallback<Set<SyllabusAttachment>> hcb = session -> {
      Criteria crit = session.createCriteria(SyllabusDataImpl.class)
                  .add(Expression.eq(SYLLABUS_DATA_ID, syllabusData.getSyllabusId()))
                  .setFetchMode(ATTACHMENTS, FetchMode.EAGER);


      SyllabusData syllabusData1 = (SyllabusData) crit.uniqueResult();

      if (syllabusData1 != null){
        return syllabusData1.getAttachments();
      }
      return new TreeSet();
    };
    return getHibernateTemplate().execute(hcb);
  }
}
 
Example #5
Source File: FooBarTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testNonlazyCollection() throws Exception {
	Session s = openSession();
	Baz baz = new Baz();
	s.save(baz);
	s.flush();
	s.connection().commit();
	s.close();

	s = openSession();
	baz = (Baz) s.createCriteria(Baz.class)
		//.setComment("criteria test")
		.setFetchMode("stringDateMap", FetchMode.EAGER)
		.uniqueResult();
	assertTrue( Hibernate.isInitialized( baz.getFooToGlarch() ) );
	assertTrue( Hibernate.isInitialized( baz.getFooComponentToFoo() ) );
	assertTrue( !Hibernate.isInitialized( baz.getStringSet() ) );
	assertTrue( Hibernate.isInitialized( baz.getStringDateMap() ) );
	s.delete(baz);
	s.flush();
	s.connection().commit();
	s.close();

}
 
Example #6
Source File: AppResource.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * The @GET annotation causes this method to be invoked whenever an HTTP GET request is received for 
 * the registered URL. 
 */
@GET
public App getAppData( @PathParam("appId") Long appId ) {
	// Initialize Hibernate
	Session session = StartupDataLoader.openSession();
	session.beginTransaction();
	
	// Fetch an App for the given ID, using eager fetching.  The conversion to JSON happens after the 
	// Hibernate Session is closed... so if lazy fetching were used, then the JSON converter would fail 
	// when trying to access associated objects.
	Criteria criteria = session.createCriteria(App.class);
	criteria.add( Restrictions.eq("id", appId) );
	criteria.setFetchMode("supportedDevices", FetchMode.SELECT);
	criteria.setFetchMode("customerReviews", FetchMode.SELECT);
	App app = (App) criteria.uniqueResult();
	
	// Cleanup Hibernate
	session.getTransaction().commit();
	session.clear();
	session.close();
	
	return app;
}
 
Example #7
Source File: GradebookManagerImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public SortedSet getStudentGradesForGradebook(final Gradebook gradebook)
		throws IllegalArgumentException {
	if (gradebook == null) {
		throw new IllegalArgumentException("Null Argument");
	} else {
		HibernateCallback hcb = session -> {
               // get syllabi in an eager fetch mode
               Criteria crit = session.createCriteria(Gradebook.class).add(
                       Expression.eq(ID, gradebook.getId())).setFetchMode(STUDENTS,
                       FetchMode.EAGER);

               Gradebook grades = (Gradebook) crit.uniqueResult();

               if (grades != null) {
                   return grades.getStudents();
               }
               return new TreeSet();
           };
		return (SortedSet) getHibernateTemplate().execute(hcb);
	}
}
 
Example #8
Source File: AnnotationBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void bindFetchProfile(FetchProfile fetchProfileAnnotation, MetadataBuildingContext context) {
	for ( FetchProfile.FetchOverride fetch : fetchProfileAnnotation.fetchOverrides() ) {
		org.hibernate.annotations.FetchMode mode = fetch.mode();
		if ( !mode.equals( org.hibernate.annotations.FetchMode.JOIN ) ) {
			throw new MappingException( "Only FetchMode.JOIN is currently supported" );
		}

		context.getMetadataCollector().addSecondPass(
				new VerifyFetchProfileReferenceSecondPass(
						fetchProfileAnnotation.name(),
						fetch,
						context
				)
		);
	}
}
 
Example #9
Source File: JoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Does the mapping, and Hibernate default semantics, specify that
 * this association should be fetched by outer joining
 */
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type) 
throws MappingException {
	if ( !type.isEntityType() && !type.isCollectionType() ) {
		return false;
	}
	else {
		if (config==FetchMode.JOIN) return true;
		if (config==FetchMode.SELECT) return false;
		if ( type.isEntityType() ) {
			//TODO: look at the owning property and check that it 
			//      isn't lazy (by instrumentation)
			EntityType entityType =(EntityType) type;
			EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
			return !persister.hasProxy();
		}
		else {
			return false;
		}
	}
}
 
Example #10
Source File: JoinWalker.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Get the join type (inner, outer, etc) or -1 if the
 * association should not be joined. Override on
 * subclasses.
 */
protected int getJoinType(
		AssociationType type, 
		FetchMode config, 
		String path, 
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth, 
		CascadeStyle cascadeStyle)
throws MappingException {
	
	if  ( !isJoinedFetchEnabled(type, config, cascadeStyle) ) return -1;
	
	if ( isTooDeep(currentDepth) || ( type.isCollectionType() && isTooManyCollections() ) ) return -1;
	
	final boolean dupe = isDuplicateAssociation(lhsTable,  lhsColumns, type);
	if (dupe) return -1;
	
	return getJoinType(nullable, currentDepth);
	
}
 
Example #11
Source File: AppResource.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * The @GET annotation causes this method to be invoked whenever an HTTP GET request is received for 
 * the registered URL. 
 */
@GET
public App getAppData( @PathParam("appId") Long appId ) {
	
	// Start a Hibernate session, using the Hibernate SessionFactory created by MasterNodeInitializer or SlaveNodeInitializer.
	String mode = (String) context.getAttribute("mode");
	Session session = mode.equals("master") ? MasterNodeInitializer.openSession() : SlaveNodeInitializer.openSession();
	session.beginTransaction();
	
	// Fetch an App for the given ID, using eager fetching.  The conversion to JSON happens after the 
	// Hibernate Session is closed... so if lazy fetching were used, then the JSON converter would fail 
	// when trying to access associated objects.
	Criteria criteria = session.createCriteria(App.class);
	criteria.add( Restrictions.eq("id", appId) );
	criteria.setFetchMode("supportedDevices", FetchMode.SELECT);
	criteria.setFetchMode("customerReviews", FetchMode.SELECT);
	App app = (App) criteria.uniqueResult();
	
	// Cleanup Hibernate
	session.getTransaction().commit();
	session.clear();
	session.close();
	
	return app;
}
 
Example #12
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
/**
 */
protected void bindManyToOneValues(org.grails.datastore.mapping.model.types.Association property, ManyToOne manyToOne) {
    PropertyConfig config = getPropertyConfig(property);

    if (config != null && config.getFetchMode() != null) {
        manyToOne.setFetchMode(config.getFetchMode());
    }
    else {
        manyToOne.setFetchMode(FetchMode.DEFAULT);
    }

    manyToOne.setLazy(getLaziness(property));

    if (config != null) {
        manyToOne.setIgnoreNotFound(config.getIgnoreNotFound());
    }

    // set referenced entity
    manyToOne.setReferencedEntityName(property.getAssociatedEntity().getName());
}
 
Example #13
Source File: WhereTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void testWhere() {
	Session s = openSession();
	s.getTransaction().begin();
	File parent = new File("parent", null);
	s.persist( parent );
	s.persist( new File("child", parent) );
	File deletedChild = new File("deleted child", parent);
	deletedChild.setDeleted(true);
	s.persist( deletedChild );
	File deletedParent = new File("deleted parent", null);
	deletedParent.setDeleted(true);
	s.persist( deletedParent );
	s.flush();
	s.clear();
	parent = (File) s.createCriteria(File.class)
			.setFetchMode("children", FetchMode.JOIN)
			.add( Restrictions.isNull("parent") )
			.uniqueResult();
	assertEquals( parent.getChildren().size(), 1 );
	s.clear();
	parent = (File) s.createQuery("from File f left join fetch f.children where f.parent is null")
		.uniqueResult();
	assertEquals( parent.getChildren().size(), 1 );
	s.getTransaction().commit();
	s.close();
}
 
Example #14
Source File: SyllabusManagerImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * getSyllabiForSyllabusItem returns the collection of syllabi
 * @param syllabusItem
 */
public Set getSyllabiForSyllabusItem(final SyllabusItem syllabusItem)
{
  if (syllabusItem == null)
  {
    throw new IllegalArgumentException("Null Argument");
  }
  else
  {                 
    HibernateCallback<Set> hcb = session -> {
      // get syllabi in an eager fetch mode
      Criteria crit = session.createCriteria(SyllabusItemImpl.class)
                  .add(Expression.eq(SURROGATE_KEY, syllabusItem.getSurrogateKey()))
                  .setFetchMode(SYLLABI, FetchMode.EAGER);


      SyllabusItem syllabusItem1 = (SyllabusItem) crit.uniqueResult();

      if (syllabusItem1 != null){
        return syllabusItem1.getSyllabi();
      }
      return new TreeSet();
    };
    return getHibernateTemplate().execute(hcb);
  }
}
 
Example #15
Source File: CriteriaJoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected JoinType getJoinType(
		AssociationType associationType,
		FetchMode config,
		PropertyPath path,
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth,
		CascadeStyle cascadeStyle) throws MappingException {
	return getJoinType(
			null,
			path,
			-1,
			associationType,
			config,
			cascadeStyle,
			lhsTable,
			lhsColumns,
			nullable,
			currentDepth
	);
}
 
Example #16
Source File: BaselineAttributeInformation.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public BaselineAttributeInformation(
		boolean lazy,
		boolean insertable,
		boolean updateable,
		ValueGeneration valueGenerationStrategy,
		boolean nullable,
		boolean dirtyCheckable,
		boolean versionable,
		CascadeStyle cascadeStyle,
		FetchMode fetchMode) {
	this.lazy = lazy;
	this.insertable = insertable;
	this.updateable = updateable;
	this.valueGenerationStrategy = valueGenerationStrategy;
	this.nullable = nullable;
	this.dirtyCheckable = dirtyCheckable;
	this.versionable = versionable;
	this.cascadeStyle = cascadeStyle;
	this.fetchMode = fetchMode;
}
 
Example #17
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Does the mapping, and Hibernate default semantics, specify that
 * this association should be fetched by outer joining
 */
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type)
		throws MappingException {
	if ( !type.isEntityType() && !type.isCollectionType() ) {
		return false;
	}
	else {
		if ( config == FetchMode.JOIN ) {
			return true;
		}
		if ( config == FetchMode.SELECT ) {
			return false;
		}
		if ( type.isEntityType() ) {
			//TODO: look at the owning property and check that it 
			//      isn't lazy (by instrumentation)
			EntityType entityType = (EntityType) type;
			EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
			return !persister.hasProxy();
		}
		else {
			return false;
		}
	}
}
 
Example #18
Source File: JoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Determine the appropriate associationType of join (if any) to use to fetch the
 * given association.
 *
 * @param associationType The association associationType.
 * @param config The metadata-defined fetch mode.
 * @param path The path to the association
 * @param lhsTable The owner table
 * @param lhsColumns The owner join columns
 * @param nullable Is the association nullable.
 * @param currentDepth Current join depth
 * @param cascadeStyle The metadata-defined cascade style.
 *
 * @return type of join to use ({@link org.hibernate.sql.JoinType#INNER_JOIN},
 * {@link org.hibernate.sql.JoinType#LEFT_OUTER_JOIN}, or -1 to indicate no joining.
 *
 * @throws MappingException ??
 */
protected JoinType getJoinType(
		AssociationType associationType,
		FetchMode config,
		PropertyPath path,
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth,
		CascadeStyle cascadeStyle) throws MappingException {
	if ( !isJoinedFetchEnabled( associationType, config, cascadeStyle ) ) {
		return JoinType.NONE;
	}
	if ( isTooDeep( currentDepth ) || ( associationType.isCollectionType() && isTooManyCollections() ) ) {
		return JoinType.NONE;
	}
	if ( isDuplicateAssociation( lhsTable, lhsColumns, associationType ) ) {
		return JoinType.NONE;
	}
	return getJoinType( nullable, currentDepth );
}
 
Example #19
Source File: TargetDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
/**
 * Find all the groups that need to be end dated.
 * @return A List of groups to be end dated.
 */
@SuppressWarnings("unchecked")
public List<TargetGroup> findEndedGroups() {
	return getHibernateTemplate().executeFind(new HibernateCallback() {
		public Object doInHibernate(Session aSession) throws HibernateException, SQLException {
			List<TargetGroup> results = aSession.createCriteria(TargetGroup.class)
				.add(Restrictions.ne("state", TargetGroup.STATE_ACTIVE))
				.add(Restrictions.lt("toDate", new Date()))
				.setFetchMode("schedules", FetchMode.JOIN)
				.setFetchMode("parents", FetchMode.JOIN)
				.setFetchMode("children", FetchMode.JOIN)
				.list();
			
			log.debug("Found " + results.size() + " groups that need to be unscheduled");
			
			return results;
		}
	});
}
 
Example #20
Source File: ProfileDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public WallItemComment getWallItemComment(final long wallItemCommentId) {

	final HibernateCallback<List<WallItemComment>> hcb = session -> session.createCriteria(WallItemComment.class)
               .add(Restrictions.eq(ID, wallItemCommentId))
               .setFetchMode("wallItem", FetchMode.JOIN)
               .list();

	final List<WallItemComment> comments = getHibernateTemplate().execute(hcb);

	if (comments.size() > 0) {
	    return comments.get(0);
	} else {
		return null;
	}
}
 
Example #21
Source File: SchedulerDBManager.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
public List<JobUsage> getUsage(final String userName, final Date startDate, final Date endDate) {
    return executeReadOnlyTransaction(session -> {
        if (startDate == null || endDate == null) {
            throw new DatabaseManagerException("Start and end dates can't be null.");
        }

        Criteria criteria = session.createCriteria(JobData.class);
        criteria.setFetchMode("tasks", FetchMode.JOIN);
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        if (userName != null) {
            criteria.add(Restrictions.eq("owner", userName));
        }
        // exclude killed but not started jobs
        criteria.add(Restrictions.gt("startTime", -1L));
        criteria.add(Restrictions.and(Restrictions.ge("finishedTime", startDate.getTime()),
                                      Restrictions.le("finishedTime", endDate.getTime())));

        List<JobData> jobsList = criteria.list();

        return jobsList.stream().map(JobData::toJobUsage).collect(Collectors.toList());
    });
}
 
Example #22
Source File: ComponentType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public ComponentType(TypeFactory.TypeScope typeScope, ComponentMetamodel metamodel) {
	this.typeScope = typeScope;
	// for now, just "re-flatten" the metamodel since this is temporary stuff anyway (HHH-1907)
	this.isKey = metamodel.isKey();
	this.propertySpan = metamodel.getPropertySpan();
	this.propertyNames = new String[propertySpan];
	this.propertyTypes = new Type[propertySpan];
	this.propertyValueGenerationStrategies = new ValueGeneration[propertySpan];
	this.propertyNullability = new boolean[propertySpan];
	this.cascade = new CascadeStyle[propertySpan];
	this.joinedFetch = new FetchMode[propertySpan];

	for ( int i = 0; i < propertySpan; i++ ) {
		StandardProperty prop = metamodel.getProperty( i );
		this.propertyNames[i] = prop.getName();
		this.propertyTypes[i] = prop.getType();
		this.propertyNullability[i] = prop.isNullable();
		this.cascade[i] = prop.getCascadeStyle();
		this.joinedFetch[i] = prop.getFetchMode();
		if ( !prop.isNullable() ) {
			hasNotNullProperty = true;
		}
		this.propertyValueGenerationStrategies[i] = prop.getValueGenerationStrategy();
	}

	this.entityMode = metamodel.getEntityMode();
	this.componentTuplizer = metamodel.getComponentTuplizer();
	this.createEmptyCompositesEnabled = metamodel.isCreateEmptyCompositesEnabled();
}
 
Example #23
Source File: DynamicFilterTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testCriteriaQueryFilters() {
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// Criteria-query test
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	log.info( "Starting Criteria-query filter tests" );
	TestData testData = new TestData();
	testData.prepare();

	Session session = openSession();
	session.enableFilter( "region" ).setParameter( "region", "APAC" );

	session.enableFilter( "fulfilledOrders" )
	        .setParameter( "asOfDate", testData.lastMonth.getTime() );

	session.enableFilter( "effectiveDate" )
	        .setParameter( "asOfDate", testData.lastMonth.getTime() );

	log.info( "Criteria query against Salesperson..." );
	List salespersons = session.createCriteria( Salesperson.class )
	        .setFetchMode( "orders", FetchMode.JOIN )
	        .list();
	assertEquals( "Incorrect salesperson count", 1, salespersons.size() );
	assertEquals( "Incorrect order count", 1, ( ( Salesperson ) salespersons.get( 0 ) ).getOrders().size() );

	log.info( "Criteria query against Product..." );
	List products = session.createCriteria( Product.class )
	        .add( Expression.eq( "stockNumber", new Integer( 124 ) ) )
	        .list();
	assertEquals( "Incorrect product count", 1, products.size() );

	session.close();
	testData.release();
}
 
Example #24
Source File: StandardProperty.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs NonIdentifierProperty instances.
 *
 * @param name The name by which the property can be referenced within
 * its owner.
 * @param type The Hibernate Type of this property.
 * @param lazy Should this property be handled lazily?
 * @param insertable Is this property an insertable value?
 * @param updateable Is this property an updateable value?
 * @param valueGenerationStrategy How (if) values for this attribute are generated
 * @param nullable Is this property a nullable value?
 * @param checkable Is this property a checkable value?
 * @param versionable Is this property a versionable value?
 * @param cascadeStyle The cascade style for this property's value.
 * @param fetchMode Any fetch mode defined for this property
 */
public StandardProperty(
		String name,
		Type type,
		boolean lazy,
		boolean insertable,
		boolean updateable,
		ValueGeneration valueGenerationStrategy,
		boolean nullable,
		boolean checkable,
		boolean versionable,
		CascadeStyle cascadeStyle,
		FetchMode fetchMode) {
	super(
			null,
			null,
			-1,
			name,
			type,
			new BaselineAttributeInformation.Builder()
					.setLazy( lazy )
					.setInsertable( insertable )
					.setUpdateable( updateable )
					.setValueGenerationStrategy( valueGenerationStrategy )
					.setNullable( nullable )
					.setDirtyCheckable( checkable )
					.setVersionable( versionable )
					.setCascadeStyle( cascadeStyle )
					.setFetchMode( fetchMode )
					.createInformation()
	);
}
 
Example #25
Source File: CustomFieldRepositoryImpl.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Override
public Page<CustomField> search(CustomFieldSearchRequest request, Pageable pageable) {
	Session session = (Session) entityManager.getDelegate();
	Criteria criteria = session.createCriteria(CustomField.class)
			.setFetchMode("options", FetchMode.JOIN);

	FullTextQuery persistenceQuery = buildFullTextQuery(request, pageable, criteria);
	int resultSize = persistenceQuery.getResultSize();
	List<CustomField> results = persistenceQuery.getResultList();
	return new PageImpl<>(results, pageable, resultSize);
}
 
Example #26
Source File: CollectionCollaboratorRepositoryImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<Collection> getCollectionByCollaborator(Long userId, Integer start, Integer limit, boolean trashed) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionCollaborator.class);
	criteria.createAlias("collection", "col").setFetchMode("col", FetchMode.JOIN);
	criteria.add(Restrictions.eq("account.id", userId));
	
	if(trashed) {
		criteria.add(Restrictions.eq("col.status", CollectionStatus.TRASHED)); 
	} else {
		criteria.add(Restrictions.ne("col.status", CollectionStatus.TRASHED));
	}
	
//	"Case col.status When '0' Then 1 When '5' Then 2 Else 3 End";
	//"Case start_date When null Then 1 Else start_date*-1  End"
	
	if(start != null) {
		criteria.setFirstResult(start);
	}
	if(limit != null) {
		criteria.setMaxResults(limit);
	}
	
	List<CollectionCollaborator> collectionCollaborators = (List<CollectionCollaborator>) criteria.list();
	
	List<Collection> collections = new ArrayList<Collection>();
	if(collectionCollaborators != null) {
		for(CollectionCollaborator collaborator : collectionCollaborators) {
			collections.add(collaborator.getCollection());
		}
	}
	Collections.sort(collections, new CollectionComparator());
	return collections;
}
 
Example #27
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
protected void bindOneToOne(final org.grails.datastore.mapping.model.types.OneToOne property, OneToOne oneToOne,
                            String path, String sessionFactoryBeanName) {
    PropertyConfig config = getPropertyConfig(property);
    final Association otherSide = property.getInverseSide();

    final boolean hasOne = isHasOne(otherSide);
    oneToOne.setConstrained(hasOne);
    oneToOne.setForeignKeyType(oneToOne.isConstrained() ?
            ForeignKeyDirection.FROM_PARENT :
            ForeignKeyDirection.TO_PARENT);
    oneToOne.setAlternateUniqueKey(true);

    if (config != null && config.getFetchMode() != null) {
        oneToOne.setFetchMode(config.getFetchMode());
    }
    else {
        oneToOne.setFetchMode(FetchMode.DEFAULT);
    }

    oneToOne.setReferencedEntityName(otherSide.getOwner().getName());
    oneToOne.setPropertyName(property.getName());
    oneToOne.setReferenceToPrimaryKey(false);

    bindOneToOneInternal(property, oneToOne, path);

    if (hasOne) {
        PropertyConfig pc = getPropertyConfig(property);
        bindSimpleValue(property, oneToOne, path, pc, sessionFactoryBeanName);
    }
    else {
        oneToOne.setReferencedPropertyName(otherSide.getName());
    }
}
 
Example #28
Source File: Main.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Demonstrates query by criteria with runtime fetch strategy
 */
public void viewUserAuctions(Long sellerId) throws Exception {
	System.out.println("Viewing user and auctions: " + sellerId);

	Session s = factory.openSession();
	Transaction tx=null;
	try {
		tx = s.beginTransaction();

		List list = s.createCriteria(User.class)
			.add( Expression.eq("id", sellerId) )
			.setFetchMode("auctions", FetchMode.JOIN)
			.list();

		if (list.size()==0) throw new IllegalArgumentException("No user for the given id: " + sellerId);
		User user = (User) list.get(0);
		System.out.println(
			"User: " + user.getId() + " - " + user.getName() +
			", email: " + user.getEmail() +
			", auctions: " + user.getAuctions()
		);

		tx.commit();
	}
	catch (Exception e) {
		if (tx!=null) tx.rollback();
		throw e;
	}
	finally {
		s.close();
	}
}
 
Example #29
Source File: GrailsHibernateQueryUtils.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the fetch mode for the specified instance; otherwise returns the default FetchMode.
 *
 * @param object The object, converted to a string
 * @return The FetchMode
 */
public static FetchMode getFetchMode(Object object) {
    String name = object != null ? object.toString() : "default";
    if (name.equalsIgnoreCase(FetchMode.JOIN.toString()) || name.equalsIgnoreCase("eager")) {
        return FetchMode.JOIN;
    }
    if (name.equalsIgnoreCase(FetchMode.SELECT.toString()) || name.equalsIgnoreCase("lazy")) {
        return FetchMode.SELECT;
    }
    return FetchMode.DEFAULT;
}
 
Example #30
Source File: UserService.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves corresponding users at the given criteria.
 *
 * @param criteria criteria contains filter and order of required collection.
 * @param skip     number of skipped valid results.
 * @param top      max of valid results.
 * @return a list of {@link User}
 */
@Transactional(readOnly = true)
public List<User> getUsers (DetachedCriteria criteria, int skip, int top)
{
   if (criteria == null)
   {
      criteria = DetachedCriteria.forClass (User.class);
   }
   criteria.setFetchMode("roles", FetchMode.SELECT);
   criteria.setFetchMode("restrictions", FetchMode.SELECT);
   List<User> result = userDao.listCriteria (criteria, skip, top);
   return result;
}