org.hibernate.mapping.Collection Java Examples

The following examples show how to use org.hibernate.mapping.Collection. 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: ExcelPublicUtil.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
	 * 判断是不是集合的实现类
	 * @param clazz
	 * @return
	 */
	public static boolean isCollection(Class<?> clazz) {
		return clazz.isAssignableFrom(List.class)||
				clazz.isAssignableFrom(Set.class)||
				clazz.isAssignableFrom(Collection.class);
//		String colleciton = "java.util.Collection";
//		Class<?>[] faces = clazz.getInterfaces();
//		for (Class<?> face : faces) {
//			if(face.getName().equals(colleciton)){
//				return true;
//			}else{
//				if(face.getSuperclass()!= Object.class&&face.getSuperclass()!=null){
//					return isCollection(face.getSuperclass());
//				}
//			}
//		}
//		if(clazz.getSuperclass()!= Object.class&&clazz.getSuperclass()!=null){
//			return isCollection(clazz.getSuperclass());
//		}
//		return false;
	}
 
Example #2
Source File: AttributeFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public static PluralAttribute.CollectionType determineCollectionType(Class javaType) {
	if ( java.util.List.class.isAssignableFrom( javaType ) ) {
		return PluralAttribute.CollectionType.LIST;
	}
	else if ( java.util.Set.class.isAssignableFrom( javaType ) ) {
		return PluralAttribute.CollectionType.SET;
	}
	else if ( java.util.Map.class.isAssignableFrom( javaType ) ) {
		return PluralAttribute.CollectionType.MAP;
	}
	else if ( java.util.Collection.class.isAssignableFrom( javaType ) ) {
		return PluralAttribute.CollectionType.COLLECTION;
	}
	else if ( javaType.isArray() ) {
		return PluralAttribute.CollectionType.LIST;
	}
	else {
		throw new IllegalArgumentException( "Expecting collection type [" + javaType.getName() + "]" );
	}
}
 
Example #3
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void addCollectionBinding(Collection collection) throws DuplicateMappingException {
	final String collectionRole = collection.getRole();
	if ( collectionBindingMap.containsKey( collectionRole ) ) {
		throw new DuplicateMappingException( DuplicateMappingException.Type.COLLECTION, collectionRole );
	}
	collectionBindingMap.put( collectionRole, collection );

	final AccessType accessType = AccessType.fromExternalName( collection.getCacheConcurrencyStrategy() );
	if ( accessType != null ) {
		locateCacheRegionConfigBuilder( collection.getCacheRegionName() ).addCollectionConfig(
				collection,
				accessType
		);
	}
}
 
Example #4
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the DependentValue object that forms a primary key reference for the collection.
 *
 * @param mappings
 * @param property          The grails property
 * @param collection        The collection object
 * @param persistentClasses
 * @return The DependantValue (key)
 */
protected DependantValue createPrimaryKeyValue(InFlightMetadataCollector mappings, PersistentProperty property,
                                               Collection collection, Map<?, ?> persistentClasses) {
    KeyValue keyValue;
    DependantValue key;
    String propertyRef = collection.getReferencedPropertyName();
    // this is to support mapping by a property
    if (propertyRef == null) {
        keyValue = collection.getOwner().getIdentifier();
    } else {
        keyValue = (KeyValue) collection.getOwner().getProperty(propertyRef).getValue();
    }

    if (LOG.isDebugEnabled())
        LOG.debug("[GrailsDomainBinder] creating dependant key value  to table [" + keyValue.getTable().getName() + "]");

    key = new DependantValue(metadataBuildingContext, collection.getCollectionTable(), keyValue);

    key.setTypeName(null);
    // make nullable and non-updateable
    key.setNullable(true);
    key.setUpdateable(false);
    return key;
}
 
Example #5
Source File: CollectionBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static void checkFilterConditions(Collection collValue) {
	//for now it can't happen, but sometime soon...
	if ( ( collValue.getFilters().size() != 0 || StringHelper.isNotEmpty( collValue.getWhere() ) ) &&
			collValue.getFetchMode() == FetchMode.JOIN &&
			!( collValue.getElement() instanceof SimpleValue ) && //SimpleValue (CollectionOfElements) are always SELECT but it does not matter
			collValue.getElement().getFetchMode() != FetchMode.JOIN ) {
		throw new MappingException(
				"@ManyToMany or @CollectionOfElements defining filter or where without join fetching "
						+ "not valid within collection using join fetching[" + collValue.getRole() + "]"
		);
	}
}
 
Example #6
Source File: PersisterFactory.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static CollectionPersister createCollectionPersister(Configuration cfg, Collection model, CacheConcurrencyStrategy cache, SessionFactoryImplementor factory)
throws HibernateException {
	Class persisterClass = model.getCollectionPersisterClass();
	if(persisterClass==null) { // default behavior
		return model.isOneToMany() ?
			(CollectionPersister) new OneToManyPersister(model, cache, cfg, factory) :
			(CollectionPersister) new BasicCollectionPersister(model, cache, cfg, factory);
	}
	else {
		return create(persisterClass, cfg, model, cache, factory);
	}

}
 
Example #7
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Links a bidirectional one-to-many, configuring the inverse side and using a column copy to perform the link
 *
 * @param collection      The collection one-to-many
 * @param associatedClass The associated class
 * @param key             The key
 * @param otherSide       The other side of the relationship
 */
protected void linkBidirectionalOneToMany(Collection collection, PersistentClass associatedClass, DependantValue key, PersistentProperty otherSide) {
    collection.setInverse(true);

    // Iterator mappedByColumns = associatedClass.getProperty(otherSide.getName()).getValue().getColumnIterator();
    Iterator<?> mappedByColumns = getProperty(associatedClass, otherSide.getName()).getValue().getColumnIterator();
    while (mappedByColumns.hasNext()) {
        Column column = (Column) mappedByColumns.next();
        linkValueUsingAColumnCopy(otherSide, column, key);
    }
}
 
Example #8
Source File: BasicCollectionPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public BasicCollectionPersister(Collection collection,
								CacheConcurrencyStrategy cache,
								Configuration cfg,
								SessionFactoryImplementor factory)
		throws MappingException, CacheException {
	super( collection, cache, cfg, factory );
}
 
Example #9
Source File: MetadataImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public java.util.Collection<Table> collectTableMappings() {
	ArrayList<Table> tables = new ArrayList<>();
	for ( Namespace namespace : database.getNamespaces() ) {
		tables.addAll( namespace.getTables() );
	}
	return tables;
}
 
Example #10
Source File: OneToManyPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public OneToManyPersister(Collection collection,
						  CacheConcurrencyStrategy cache,
						  Configuration cfg,
						  SessionFactoryImplementor factory)
		throws MappingException, CacheException {
	super( collection, cache, cfg, factory );
	cascadeDeleteEnabled = collection.getKey().isCascadeDeleteEnabled() &&
			factory.getDialect().supportsCascadeDelete();
	keyIsNullable = collection.getKey().isNullable();
	keyIsUpdateable = collection.getKey().isUpdateable();
}
 
Example #11
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Binds the sub classes of a root class using table-per-heirarchy inheritance mapping
 *
 * @param domainClass The root domain class to bind
 * @param parent      The parent class instance
 * @param mappings    The mappings instance
 * @param sessionFactoryBeanName  the session factory bean name
 */
protected void bindSubClasses(HibernatePersistentEntity domainClass, PersistentClass parent,
                              InFlightMetadataCollector mappings, String sessionFactoryBeanName) {
    final java.util.Collection<PersistentEntity> subClasses = domainClass.getMappingContext().getDirectChildEntities(domainClass);

    for (PersistentEntity sub : subClasses) {
        final Class javaClass = sub.getJavaClass();
        if (javaClass.getSuperclass().equals(domainClass.getJavaClass()) && ConnectionSourcesSupport.usesConnectionSource(sub, dataSourceName)) {
            bindSubClass((HibernatePersistentEntity)sub, parent, mappings, sessionFactoryBeanName);
        }
    }
}
 
Example #12
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected AbstractPluralAttributeSecondPass(
		MappingDocument mappingDocument,
		PluralAttributeSource pluralAttributeSource,
		Collection collectionBinding) {
	this.mappingDocument = mappingDocument;
	this.pluralAttributeSource = pluralAttributeSource;
	this.collectionBinding = collectionBinding;
}
 
Example #13
Source File: MetadataImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public SessionFactoryBuilder getSessionFactoryBuilder() {
	final SessionFactoryBuilderImpl defaultBuilder = new SessionFactoryBuilderImpl( this, bootstrapContext );

	final ClassLoaderService cls = metadataBuildingOptions.getServiceRegistry().getService( ClassLoaderService.class );
	final java.util.Collection<SessionFactoryBuilderFactory> discoveredBuilderFactories = cls.loadJavaServices( SessionFactoryBuilderFactory.class );

	SessionFactoryBuilder builder = null;
	List<String> activeFactoryNames = null;

	for ( SessionFactoryBuilderFactory discoveredBuilderFactory : discoveredBuilderFactories ) {
		final SessionFactoryBuilder returnedBuilder = discoveredBuilderFactory.getSessionFactoryBuilder( this, defaultBuilder );
		if ( returnedBuilder != null ) {
			if ( activeFactoryNames == null ) {
				activeFactoryNames = new ArrayList<>();
			}
			activeFactoryNames.add( discoveredBuilderFactory.getClass().getName() );
			builder = returnedBuilder;
		}
	}

	if ( activeFactoryNames != null && activeFactoryNames.size() > 1 ) {
		throw new HibernateException(
				"Multiple active SessionFactoryBuilderFactory definitions were discovered : " +
						String.join(", ", activeFactoryNames)
		);
	}

	if ( builder != null ) {
		return builder;
	}

	return defaultBuilder;
}
 
Example #14
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
protected void bindCollectionForPropertyConfig(Collection collection, PropertyConfig config) {
    if (config == null) {
        collection.setLazy(true);
        collection.setExtraLazy(false);
    } else {
        final FetchMode fetch = config.getFetchMode();
        if(!fetch.equals(FetchMode.JOIN) && !fetch.equals(FetchMode.EAGER)) {
            collection.setLazy(true);
        }
        final Boolean lazy = config.getLazy();
        if(lazy != null) {
            collection.setExtraLazy(lazy);
        }
    }
}
 
Example #15
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void processExportableProducers() {
	// for now we only handle id generators as ExportableProducers

	final Dialect dialect = getDatabase().getJdbcEnvironment().getDialect();
	final String defaultCatalog = extractName( getDatabase().getDefaultNamespace().getName().getCatalog(), dialect );
	final String defaultSchema = extractName( getDatabase().getDefaultNamespace().getName().getSchema(), dialect );

	for ( PersistentClass entityBinding : entityBindingMap.values() ) {
		if ( entityBinding.isInherited() ) {
			continue;
		}

		handleIdentifierValueBinding(
				entityBinding.getIdentifier(),
				dialect,
				defaultCatalog,
				defaultSchema,
				(RootClass) entityBinding
		);
	}

	for ( Collection collection : collectionBindingMap.values() ) {
		if ( !IdentifierCollection.class.isInstance( collection ) ) {
			continue;
		}

		handleIdentifierValueBinding(
				( (IdentifierCollection) collection ).getIdentifier(),
				dialect,
				defaultCatalog,
				defaultSchema,
				null
		);
	}
}
 
Example #16
Source File: ExecutionEnvironment.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void applyCacheSettings(Configuration configuration) {
	if ( settings.getCacheConcurrencyStrategy() != null ) {
		Iterator iter = configuration.getClassMappings();
		while ( iter.hasNext() ) {
			PersistentClass clazz = (PersistentClass) iter.next();
			Iterator props = clazz.getPropertyClosureIterator();
			boolean hasLob = false;
			while ( props.hasNext() ) {
				Property prop = (Property) props.next();
				if ( prop.getValue().isSimpleValue() ) {
					String type = ( ( SimpleValue ) prop.getValue() ).getTypeName();
					if ( "blob".equals(type) || "clob".equals(type) ) {
						hasLob = true;
					}
					if ( Blob.class.getName().equals(type) || Clob.class.getName().equals(type) ) {
						hasLob = true;
					}
				}
			}
			if ( !hasLob && !clazz.isInherited() && settings.overrideCacheStrategy() ) {
				configuration.setCacheConcurrencyStrategy( clazz.getEntityName(), settings.getCacheConcurrencyStrategy() );
			}
		}
		iter = configuration.getCollectionMappings();
		while ( iter.hasNext() ) {
			Collection coll = (Collection) iter.next();
			configuration.setCollectionCacheConcurrencyStrategy( coll.getRole(), settings.getCacheConcurrencyStrategy() );
		}
	}
}
 
Example #17
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void processCachingOverrides() {
	if ( bootstrapContext.getCacheRegionDefinitions() == null ) {
		return;
	}

	for ( CacheRegionDefinition cacheRegionDefinition : bootstrapContext.getCacheRegionDefinitions() ) {
		if ( cacheRegionDefinition.getRegionType() == CacheRegionDefinition.CacheRegionType.ENTITY ) {
			final PersistentClass entityBinding = getEntityBinding( cacheRegionDefinition.getRole() );
			if ( entityBinding == null ) {
				throw new HibernateException(
						"Cache override referenced an unknown entity : " + cacheRegionDefinition.getRole()
				);
			}
			if ( !RootClass.class.isInstance( entityBinding ) ) {
				throw new HibernateException(
						"Cache override referenced a non-root entity : " + cacheRegionDefinition.getRole()
				);
			}
			entityBinding.setCached( true );
			( (RootClass) entityBinding ).setCacheRegionName( cacheRegionDefinition.getRegion() );
			( (RootClass) entityBinding ).setCacheConcurrencyStrategy( cacheRegionDefinition.getUsage() );
			( (RootClass) entityBinding ).setLazyPropertiesCacheable( cacheRegionDefinition.isCacheLazy() );
		}
		else if ( cacheRegionDefinition.getRegionType() == CacheRegionDefinition.CacheRegionType.COLLECTION ) {
			final Collection collectionBinding = getCollectionBinding( cacheRegionDefinition.getRole() );
			if ( collectionBinding == null ) {
				throw new HibernateException(
						"Cache override referenced an unknown collection role : " + cacheRegionDefinition.getRole()
				);
			}
			collectionBinding.setCacheRegionName( cacheRegionDefinition.getRegion() );
			collectionBinding.setCacheConcurrencyStrategy( cacheRegionDefinition.getUsage() );
		}
	}
}
 
Example #18
Source File: DomainDataRegionConfigImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("UnusedReturnValue")
public Builder addCollectionConfig(Collection collectionDescriptor, AccessType accessType) {
	if ( collectionConfigs == null ) {
		collectionConfigs = new ArrayList<>();
	}

	collectionConfigs.add( new CollectionDataCachingConfigImpl( collectionDescriptor, accessType ) );
	return this;
}
 
Example #19
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public java.util.Collection<Table> collectTableMappings() {
	ArrayList<Table> tables = new ArrayList<>();
	for ( Namespace namespace : getDatabase().getNamespaces() ) {
		tables.addAll( namespace.getTables() );
	}
	return tables;
}
 
Example #20
Source File: CollectionDataCachingConfigImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public CollectionDataCachingConfigImpl(
		Collection collectionDescriptor,
		AccessType accessType) {
	super( accessType );
	this.collectionDescriptor = collectionDescriptor;
	this.navigableRole = new NavigableRole( collectionDescriptor.getRole() );
}
 
Example #21
Source File: GrailsDomainBinder.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Binds a root class (one with no super classes) to the runtime meta model
 * based on the supplied Grails domain class
 *
 * @param entity The Grails domain class
 * @param mappings    The Hibernate Mappings object
 * @param sessionFactoryBeanName  the session factory bean name
 */
public void bindRoot(HibernatePersistentEntity entity, InFlightMetadataCollector mappings, String sessionFactoryBeanName) {
    if (mappings.getEntityBinding(entity.getName()) != null) {
        LOG.info("[GrailsDomainBinder] Class [" + entity.getName() + "] is already mapped, skipping.. ");
        return;
    }

    RootClass root = new RootClass(this.metadataBuildingContext);
    root.setAbstract(entity.isAbstract());
    final MappingContext mappingContext = entity.getMappingContext();



    final java.util.Collection<PersistentEntity> children = mappingContext.getDirectChildEntities(entity);
    if (children.isEmpty()) {
        root.setPolymorphic(false);
    }
    bindClass(entity, root, mappings);

    Mapping m = getMapping(entity);

    bindRootPersistentClassCommonValues(entity, root, mappings, sessionFactoryBeanName);

    if (!children.isEmpty()) {
        boolean tablePerSubclass = m != null && !m.getTablePerHierarchy();
        if (!tablePerSubclass) {
            // if the root class has children create a discriminator property
            bindDiscriminatorProperty(root.getTable(), root, mappings);
        }
        // bind the sub classes
        bindSubClasses(entity, root, mappings, sessionFactoryBeanName);
    }

    addMultiTenantFilterIfNecessary(entity, root, mappings, sessionFactoryBeanName);

    mappings.addEntityBinding(root);
}
 
Example #22
Source File: NonReflectiveBinderTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testComparator() {
	PersistentClass cm = cfg.getClassMapping("org.hibernate.test.legacy.Wicked");
	
	Property property = cm.getProperty("sortedEmployee");
	Collection col = (Collection) property.getValue();
	assertEquals(col.getComparatorClassName(),"org.hibernate.test.legacy.NonExistingComparator");
}
 
Example #23
Source File: PersisterFactoryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings( {"unchecked"})
public CollectionPersister createCollectionPersister(
		Collection collectionBinding,
		CollectionDataAccess cacheAccessStrategy,
		PersisterCreationContext creationContext) throws HibernateException {
	// If the metadata for the collection specified an explicit persister class, use it
	Class<? extends CollectionPersister> persisterClass = collectionBinding.getCollectionPersisterClass();
	if ( persisterClass == null ) {
		// Otherwise, use the persister class indicated by the PersisterClassResolver service
		persisterClass = serviceRegistry.getService( PersisterClassResolver.class )
				.getCollectionPersisterClass( collectionBinding );
	}
	return createCollectionPersister( persisterClass, collectionBinding, cacheAccessStrategy, creationContext );
}
 
Example #24
Source File: MetamodelImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void applyNamedEntityGraphs(java.util.Collection<NamedEntityGraphDefinition> namedEntityGraphs) {
	for ( NamedEntityGraphDefinition definition : namedEntityGraphs ) {
		log.debugf(
				"Applying named entity graph [name=%s, entity-name=%s, jpa-entity-name=%s",
				definition.getRegisteredName(),
				definition.getEntityName(),
				definition.getJpaEntityName()
		);
		final EntityType entityType = entity( definition.getEntityName() );
		if ( entityType == null ) {
			throw new IllegalArgumentException(
					"Attempted to register named entity graph [" + definition.getRegisteredName()
							+ "] for unknown entity ["+ definition.getEntityName() + "]"

			);
		}
		final EntityGraphImpl entityGraph = new EntityGraphImpl(
				definition.getRegisteredName(),
				entityType,
				this.getSessionFactory()
		);

		final NamedEntityGraph namedEntityGraph = definition.getAnnotation();

		if ( namedEntityGraph.includeAllAttributes() ) {
			for ( Object attributeObject : entityType.getAttributes() ) {
				entityGraph.addAttributeNodes( (Attribute) attributeObject );
			}
		}

		if ( namedEntityGraph.attributeNodes() != null ) {
			applyNamedAttributeNodes( namedEntityGraph.attributeNodes(), namedEntityGraph, entityGraph );
		}

		entityGraphMap.put( definition.getRegisteredName(), entityGraph );
	}
}
 
Example #25
Source File: Configuration.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void validate() throws MappingException {
	Iterator iter = classes.values().iterator();
	while ( iter.hasNext() ) {
		( (PersistentClass) iter.next() ).validate( mapping );
	}
	iter = collections.values().iterator();
	while ( iter.hasNext() ) {
		( (Collection) iter.next() ).validate( mapping );
	}
}
 
Example #26
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Collection getCollectionBinding(String role) {
	return collectionBindingMap.get( role );
}
 
Example #27
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void applyCaching(MappingDocument mappingDocument, Caching caching, Collection collection) {
		if ( caching == null || caching.getRequested() == TruthValue.UNKNOWN ) {
			// see if JPA's SharedCacheMode indicates we should implicitly apply caching
			switch ( mappingDocument.getBuildingOptions().getSharedCacheMode() ) {
				case ALL: {
					caching = new Caching(
							null,
							mappingDocument.getBuildingOptions().getImplicitCacheAccessType(),
							false,
							TruthValue.UNKNOWN
					);
					break;
				}
				case NONE: {
					// Ideally we'd disable all caching...
					break;
				}
				case ENABLE_SELECTIVE: {
					// this is default behavior for hbm.xml
					break;
				}
				case DISABLE_SELECTIVE: {
					// really makes no sense for hbm.xml
					break;
				}
				default: {
					// null or UNSPECIFIED, nothing to do.  IMO for hbm.xml this is equivalent
					// to ENABLE_SELECTIVE
					break;
				}
			}
		}

		if ( caching == null || caching.getRequested() == TruthValue.FALSE ) {
			return;
		}

		if ( caching.getAccessType() != null ) {
			collection.setCacheConcurrencyStrategy( caching.getAccessType().getExternalName() );
		}
		else {
			collection.setCacheConcurrencyStrategy( mappingDocument.getBuildingOptions().getImplicitCacheAccessType().getExternalName() );
		}
		collection.setCacheRegionName( caching.getRegion() );
//		collection.setCachingExplicitlyRequested( caching.getRequested() != TruthValue.UNKNOWN );
	}
 
Example #28
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Collection create(Element node, String path, PersistentClass owner,
		Mappings mappings, java.util.Map inheritedMetas) throws MappingException {
	IdentifierBag bag = new IdentifierBag( owner );
	bindCollection( node, bag, owner.getEntityName(), path, mappings, inheritedMetas );
	return bag;
}
 
Example #29
Source File: StatsTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void testCollectionFetchVsLoad() throws Exception {
	Statistics stats = getSessions().getStatistics();
	stats.clear();

	Session s = openSession();
	Transaction tx = s.beginTransaction();
	Continent europe = fillDb(s);
	tx.commit();
	s.clear();

	tx = s.beginTransaction();
	assertEquals(0, stats.getCollectionLoadCount() );
	assertEquals(0,  stats.getCollectionFetchCount() );
	Continent europe2 = (Continent) s.get( Continent.class, europe.getId() );
	assertEquals("Lazy true: no collection should be loaded", 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2.getCountries().size();
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals("Explicit fetch of the collection state", 1, stats.getCollectionFetchCount() );
	tx.commit();
	s.close();

	s = openSession();
	tx = s.beginTransaction();
	stats.clear();
	europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	assertEquals( 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2 = (Continent) s.createQuery(
			"from " + Continent.class.getName() + " a join fetch a.countries where a.id = " + europe.getId()
		).uniqueResult();
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals( "collection should be loaded in the same query as its parent", 0, stats.getCollectionFetchCount() );
	tx.commit();
	s.close();

	Collection coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
	coll.setFetchMode(FetchMode.JOIN);
	coll.setLazy(false);
	SessionFactory sf = getCfg().buildSessionFactory();
	stats = sf.getStatistics();
	stats.clear();
	stats.setStatisticsEnabled(true);
	s = sf.openSession();
	tx = s.beginTransaction();
	europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	assertEquals( 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2 = (Continent) s.get( Continent.class, europe.getId() );
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals( "Should do direct load, not indirect second load when lazy false and JOIN", 0, stats.getCollectionFetchCount() );
	tx.commit();
	s.close();
	sf.close();

	coll = getCfg().getCollectionMapping(Continent.class.getName() + ".countries");
	coll.setFetchMode(FetchMode.SELECT);
	coll.setLazy(false);
	sf = getCfg().buildSessionFactory();
	stats = sf.getStatistics();
	stats.clear();
	stats.setStatisticsEnabled(true);
	s = sf.openSession();
	tx = s.beginTransaction();
	europe = fillDb(s);
	tx.commit();
	s.clear();
	tx = s.beginTransaction();
	assertEquals( 0, stats.getCollectionLoadCount() );
	assertEquals( 0, stats.getCollectionFetchCount() );
	europe2 = (Continent) s.get( Continent.class, europe.getId() );
	assertEquals( 1, stats.getCollectionLoadCount() );
	assertEquals( "Should do explicit collection load, not part of the first one", 1, stats.getCollectionFetchCount() );
	Iterator countries = europe2.getCountries().iterator();
	while ( countries.hasNext() ) {
		s.delete( countries.next() );
	}
	cleanDb( s );
	tx.commit();
	s.close();
}
 
Example #30
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected void bindCollectionKey() {
	final PluralAttributeKeySource keySource = getPluralAttributeSource().getKeySource();
	final String propRef = keySource.getReferencedPropertyName();
	getCollectionBinding().setReferencedPropertyName( propRef );

	final KeyValue keyVal;
	if ( propRef == null ) {
		keyVal = getCollectionBinding().getOwner().getIdentifier();
	}
	else {
		keyVal = (KeyValue) getCollectionBinding().getOwner().getRecursiveProperty( propRef ).getValue();
	}
	final DependantValue key = new DependantValue(
			mappingDocument,
			getCollectionBinding().getCollectionTable(),
			keyVal
	);
	key.setForeignKeyName( keySource.getExplicitForeignKeyName() );
	key.setCascadeDeleteEnabled( getPluralAttributeSource().getKeySource().isCascadeDeleteEnabled() );

	final ImplicitJoinColumnNameSource.Nature implicitNamingNature;
	if ( getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceManyToMany
			|| getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceOneToMany ) {
		implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION;
	}
	else {
		implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION;
	}

	relationalObjectBinder.bindColumnsAndFormulas(
			mappingDocument,
			getPluralAttributeSource().getKeySource().getRelationalValueSources(),
			key,
			getPluralAttributeSource().getKeySource().areValuesNullableByDefault(),
			new RelationalObjectBinder.ColumnNamingDelegate() {
				@Override
				public Identifier determineImplicitName(final LocalMetadataBuildingContext context) {
					return context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_KEY_COLUMN_NAME );
				}
			}
	);

	key.createForeignKey();
	getCollectionBinding().setKey( key );

	key.setNullable( getPluralAttributeSource().getKeySource().areValuesNullableByDefault() );
	key.setUpdateable( getPluralAttributeSource().getKeySource().areValuesIncludedInUpdateByDefault() );
}