Java Code Examples for org.hibernate.mapping.Collection

The following examples show how to use org.hibernate.mapping.Collection. These examples are extracted from open source projects. 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 Project: lams   Source File: AttributeFactory.java    License: 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 2
Source Project: jeewx   Source File: ExcelPublicUtil.java    License: 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 3
@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 Project: gorm-hibernate5   Source File: GrailsDomainBinder.java    License: 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
public BasicCollectionPersister(Collection collection,
								CacheConcurrencyStrategy cache,
								Configuration cfg,
								SessionFactoryImplementor factory)
		throws MappingException, CacheException {
	super( collection, cache, cfg, factory );
}
 
Example 6
Source Project: gorm-hibernate5   Source File: GrailsDomainBinder.java    License: 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 7
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 8
Source Project: lams   Source File: CollectionBinder.java    License: 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 9
Source Project: gorm-hibernate5   Source File: GrailsDomainBinder.java    License: 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 10
Source Project: lams   Source File: MetamodelImpl.java    License: 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 11
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 12
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 13
Source Project: lams   Source File: PersisterFactoryImpl.java    License: 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 14
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 15
public CollectionDataCachingConfigImpl(
		Collection collectionDescriptor,
		AccessType accessType) {
	super( accessType );
	this.collectionDescriptor = collectionDescriptor;
	this.navigableRole = new NavigableRole( collectionDescriptor.getRole() );
}
 
Example 16
@SuppressWarnings("UnusedReturnValue")
public Builder addCollectionConfig(Collection collectionDescriptor, AccessType accessType) {
	if ( collectionConfigs == null ) {
		collectionConfigs = new ArrayList<>();
	}

	collectionConfigs.add( new CollectionDataCachingConfigImpl( collectionDescriptor, accessType ) );
	return this;
}
 
Example 17
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 18
Source Project: lams   Source File: ModelBinder.java    License: 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 19
@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
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 21
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 22
Source Project: lams   Source File: MetadataImpl.java    License: 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 23
Source Project: lams   Source File: MetadataImpl.java    License: 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 24
Source Project: gorm-hibernate5   Source File: GrailsDomainBinder.java    License: 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 25
Source Project: gorm-hibernate5   Source File: GrailsDomainBinder.java    License: 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 26
public CollectionSecondPass(Mappings mappings, Collection collection, java.util.Map inheritedMetas) {
	this.collection = collection;
	this.mappings = mappings;
	this.localInheritedMetas = inheritedMetas;
}
 
Example 27
public Collection getCollectionBinding() {
	return collection;
}
 
Example 28
Source Project: lams   Source File: CollectionSecondPass.java    License: GNU General Public License v2.0 4 votes vote down vote up
public CollectionSecondPass(MetadataBuildingContext buildingContext, Collection collection, java.util.Map inheritedMetas) {
	this.collection = collection;
	this.buildingContext = buildingContext;
	this.localInheritedMetas = inheritedMetas;
}
 
Example 29
Source Project: lams   Source File: CollectionSecondPass.java    License: GNU General Public License v2.0 4 votes vote down vote up
public CollectionSecondPass(MetadataBuildingContext buildingContext, Collection collection) {
	this( buildingContext, collection, Collections.EMPTY_MAP );
}
 
Example 30
Source Project: lams   Source File: CollectionBinder.java    License: GNU General Public License v2.0 4 votes vote down vote up
public Collection getCollection() {
	return collection;
}