org.hibernate.mapping.Selectable Java Examples

The following examples show how to use org.hibernate.mapping.Selectable. 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: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyMax(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
	if ( Max.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor;
		long max = maxConstraint.getAnnotation().value();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				String checkConstraint = col.getQuotedName( dialect ) + "<=" + max;
				applySQLCheck( col, checkConstraint );
			}
		}
	}
}
 
Example #2
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyMin(Property property, ConstraintDescriptor<?> descriptor, Dialect dialect) {
	if ( Min.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor;
		long min = minConstraint.getAnnotation().value();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				String checkConstraint = col.getQuotedName(dialect) + ">=" + min;
				applySQLCheck( col, checkConstraint );
			}
		}
	}
}
 
Example #3
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyDigits(Property property, ConstraintDescriptor<?> descriptor) {
	if ( Digits.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Digits> digitsConstraint = (ConstraintDescriptor<Digits>) descriptor;
		int integerDigits = digitsConstraint.getAnnotation().integer();
		int fractionalDigits = digitsConstraint.getAnnotation().fraction();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				col.setPrecision( integerDigits + fractionalDigits );
				col.setScale( fractionalDigits );
			}
		}

	}
}
 
Example #4
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applySize(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
	if ( Size.class.equals( descriptor.getAnnotation().annotationType() )
			&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
		@SuppressWarnings("unchecked")
		ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor;
		int max = sizeConstraint.getAnnotation().max();

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			Column col = (Column) selectable;
			if ( max < Integer.MAX_VALUE ) {
				col.setLength( max );
			}
		}
	}
}
 
Example #5
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static void applyLength(Property property, ConstraintDescriptor<?> descriptor, PropertyDescriptor propertyDescriptor) {
	if ( "org.hibernate.validator.constraints.Length".equals(
			descriptor.getAnnotation().annotationType().getName()
	)
			&& String.class.equals( propertyDescriptor.getElementClass() ) ) {
		@SuppressWarnings("unchecked")
		int max = (Integer) descriptor.getAttributes().get( "max" );

		@SuppressWarnings("unchecked")
		final Iterator<Selectable> itor = property.getColumnIterator();
		if ( itor.hasNext() ) {
			final Selectable selectable = itor.next();
			if ( Column.class.isInstance( selectable ) ) {
				Column col = (Column) selectable;
				if ( max < Integer.MAX_VALUE ) {
					col.setLength( max );
				}
			}
		}
	}
}
 
Example #6
Source File: MapBinder.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String getFromAndWhereFormula(
		String tableName,
		Iterator<Selectable> collectionTableColumns,
		Iterator<Selectable> referencedEntityColumns) {
	String alias = "$alias$";
	StringBuilder fromAndWhereSb = new StringBuilder( " from " )
			.append( tableName )
			//.append(" as ") //Oracle doesn't support it in subqueries
			.append( " " )
			.append( alias ).append( " where " );
	while ( collectionTableColumns.hasNext() ) {
		Column colColumn = (Column) collectionTableColumns.next();
		Column refColumn = (Column) referencedEntityColumns.next();
		fromAndWhereSb.append( alias )
				.append( '.' )
				.append( refColumn.getQuotedName() )
				.append( '=' )
				.append( colColumn.getQuotedName() )
				.append( " and " );
	}
	return fromAndWhereSb.substring( 0, fromAndWhereSb.length() - 5 );
}
 
Example #7
Source File: HibernateUtil.java    From unitime with Apache License 2.0 5 votes vote down vote up
public static void fixSchemaInFormulas(Configuration cfg) throws ClassNotFoundException {
	cfg.buildMappings();
	Class dialect = Class.forName(cfg.getProperty("dialect"));
	String schema = cfg.getProperty("default_schema");
	for (Iterator i=cfg.getClassMappings();i.hasNext();) {
        PersistentClass pc = (PersistentClass)i.next();
        for (Iterator j=pc.getPropertyIterator();j.hasNext();) {
            Property p = (Property)j.next();
            for (Iterator k=p.getColumnIterator();k.hasNext();) {
                Selectable c = (Selectable)k.next();
                if (c instanceof Formula) {
                    Formula f = (Formula)c;
                    boolean updated = false;
                    if (schema != null && f.getFormula() != null && f.getFormula().indexOf("%SCHEMA%")>=0) {
                        f.setFormula(f.getFormula().replaceAll("%SCHEMA%", schema));
                        sLog.debug("Schema updated in "+pc.getClassName()+"."+p.getName()+" to "+f.getFormula());
                    }
                    if (f.getFormula()!=null && (f.getFormula().indexOf("%TRUE%")>=0 || f.getFormula().indexOf("%FALSE%")>=0)) {
                    	if (isPostgress(dialect)) {
                    		f.setFormula(f.getFormula().replaceAll("%TRUE%", "'t'").replaceAll("%FALSE%", "'f'"));
                    	} else {
                    		f.setFormula(f.getFormula().replaceAll("%TRUE%", "1").replaceAll("%FALSE%", "0"));
                    	}
                    }
                    if (updated)
                    	sLog.debug("Schema updated in "+pc.getClassName()+"."+p.getName()+" to "+f.getFormula());
                }
            }
        }
    }
}
 
Example #8
Source File: AbstractEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void internalInitSubclassPropertyAliasesMap(String path, Iterator propertyIterator) {
	while ( propertyIterator.hasNext() ) {

		Property prop = ( Property ) propertyIterator.next();
		String propname = path == null ? prop.getName() : path + "." + prop.getName();
		if ( prop.isComposite() ) {
			Component component = ( Component ) prop.getValue();
			Iterator compProps = component.getPropertyIterator();
			internalInitSubclassPropertyAliasesMap( propname, compProps );
		}
		else {
			String[] aliases = new String[prop.getColumnSpan()];
			String[] cols = new String[prop.getColumnSpan()];
			Iterator colIter = prop.getColumnIterator();
			int l = 0;
			while ( colIter.hasNext() ) {
				Selectable thing = ( Selectable ) colIter.next();
				aliases[l] = thing.getAlias( getFactory().getDialect(), prop.getValue().getTable() );
				cols[l] = thing.getText( getFactory().getDialect() ); // TODO: skip formulas?
				l++;
			}

			subclassPropertyAliases.put( propname, aliases );
			subclassPropertyColumnNames.put( propname, cols );
		}
	}

}
 
Example #9
Source File: IgniteCacheInitializer.java    From hibernate-ogm-ignite with GNU Lesser General Public License v2.1 5 votes vote down vote up
private String fieldType(Column currentColumn) {
	Value value = currentColumn.getValue();
	Type type = value.getType();
	while ( type.isEntityType() || type.isComponentType() ) {
		if ( type.isEntityType() ) {
			type = ( (SimpleValue) value ).getMetadata().getIdentifierType( type.getName() );
		}
		if ( type.isComponentType() ) {
			int i = 0;
			boolean columnFound = false;
			// search which nested property is mapped to the given column
			for ( Iterator<Selectable> ci = value.getColumnIterator(); ci.hasNext(); ++i ) {
				if ( currentColumn.getName().equals( ci.next().getText() ) ) {
					type = ( (ComponentType) type ).getSubtypes()[i];
					columnFound = true;
					break;
				}
			}
			if ( !columnFound ) {
				throw new IllegalArgumentException( "Cannot determine type for column " + currentColumn );
			}
		}
	}
	GridType gridType = serviceRegistry.getService( TypeTranslator.class ).getType( type );
	if ( gridType instanceof EnumType ) {
		return enumFieldType( (EnumType) gridType );
	}
	if ( gridType instanceof YesNoType ) {
		return STRING_CLASS_NAME;
	}
	if ( gridType instanceof NumericBooleanType ) {
		return INTEGER_CLASS_NAME;
	}
	Class<?> returnedClass = type.getReturnedClass();
	if ( Character.class.equals( returnedClass ) ) {
		return STRING_CLASS_NAME;
	}
	return returnedClass.getName();
}
 
Example #10
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void createBackReferences() {
	super.createBackReferences();

	boolean indexIsFormula = false;
	Iterator itr = getCollectionBinding().getIndex().getColumnIterator();
	while ( itr.hasNext() ) {
		if ( ( (Selectable) itr.next() ).isFormula() ) {
			indexIsFormula = true;
		}
	}

	if ( getCollectionBinding().isOneToMany()
			&& !getCollectionBinding().getKey().isNullable()
			&& !getCollectionBinding().isInverse()
			&& !indexIsFormula ) {
		final String entityName = ( (OneToMany) getCollectionBinding().getElement() ).getReferencedEntityName();
		final PersistentClass referenced = getMappingDocument().getMetadataCollector().getEntityBinding( entityName );
		final IndexBackref ib = new IndexBackref();
		ib.setName( '_' + getCollectionBinding().getOwnerEntityName() + "." + getPluralAttributeSource().getName() + "IndexBackref" );
		ib.setUpdateable( false );
		ib.setSelectable( false );
		ib.setCollectionRole( getCollectionBinding().getRole() );
		ib.setEntityName( getCollectionBinding().getOwner().getEntityName() );
		ib.setValue( getCollectionBinding().getIndex() );
		referenced.addProperty( ib );
	}
}
 
Example #11
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String columns(Value value) {
	final StringBuilder builder = new StringBuilder();
	final Iterator<Selectable> selectableItr = value.getColumnIterator();
	while ( selectableItr.hasNext() ) {
		builder.append( selectableItr.next().getText() );
		if ( selectableItr.hasNext() ) {
			builder.append( ", " );
		}
	}
	return builder.toString();
}
 
Example #12
Source File: AbstractSchemaValidator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void validateTable(
		Table table,
		TableInformation tableInformation,
		Metadata metadata,
		ExecutionOptions options,
		Dialect dialect) {
	if ( tableInformation == null ) {
		throw new SchemaManagementException(
				String.format(
						"Schema-validation: missing table [%s]",
						table.getQualifiedTableName().toString()
				)
		);
	}

	final Iterator selectableItr = table.getColumnIterator();
	while ( selectableItr.hasNext() ) {
		final Selectable selectable = (Selectable) selectableItr.next();
		if ( Column.class.isInstance( selectable ) ) {
			final Column column = (Column) selectable;
			final ColumnInformation existingColumn = tableInformation.getColumn( Identifier.toIdentifier( column.getQuotedName() ) );
			if ( existingColumn == null ) {
				throw new SchemaManagementException(
						String.format(
								"Schema-validation: missing column [%s] in table [%s]",
								column.getName(),
								table.getQualifiedTableName()
						)
				);
			}
			validateColumnType( table, column, existingColumn, metadata, options, dialect );
		}
	}
}
 
Example #13
Source File: AbstractEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void internalInitSubclassPropertyAliasesMap(String path, Iterator propertyIterator) {
	while ( propertyIterator.hasNext() ) {

		Property prop = (Property) propertyIterator.next();
		String propname = path == null ? prop.getName() : path + "." + prop.getName();
		if ( prop.isComposite() ) {
			Component component = (Component) prop.getValue();
			Iterator compProps = component.getPropertyIterator();
			internalInitSubclassPropertyAliasesMap( propname, compProps );
		}
		else {
			String[] aliases = new String[prop.getColumnSpan()];
			String[] cols = new String[prop.getColumnSpan()];
			Iterator colIter = prop.getColumnIterator();
			int l = 0;
			while ( colIter.hasNext() ) {
				Selectable thing = (Selectable) colIter.next();
				aliases[l] = thing.getAlias( getFactory().getDialect(), prop.getValue().getTable() );
				cols[l] = thing.getText( getFactory().getDialect() ); // TODO: skip formulas?
				l++;
			}

			subclassPropertyAliases.put( propname, aliases );
			subclassPropertyColumnNames.put( propname, cols );
		}
	}

}
 
Example #14
Source File: MapBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean propertyIteratorContainsColumn(Iterator propertyIterator, Column column) {
	for ( Iterator it = propertyIterator; it.hasNext(); ) {
		final Property property = (Property) it.next();
		for ( Iterator<Selectable> selectableIterator = property.getColumnIterator(); selectableIterator.hasNext(); ) {
			final Selectable selectable = selectableIterator.next();
			if ( column.equals( selectable ) ) {
				final Column iteratedColumn = (Column) selectable;
				if ( column.getValue().getTable().equals( iteratedColumn.getValue().getTable() ) ) {
					return true;
				}
			}
		}
	}
	return false;
}
 
Example #15
Source File: MapBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void makeOneToManyMapKeyColumnNullableIfNotInProperty(
		final XProperty property) {
	final org.hibernate.mapping.Map map = (org.hibernate.mapping.Map) this.collection;
	if ( map.isOneToMany() &&
			property.isAnnotationPresent( MapKeyColumn.class ) ) {
		final Value indexValue = map.getIndex();
		if ( indexValue.getColumnSpan() != 1 ) {
			throw new AssertionFailure( "Map key mapped by @MapKeyColumn does not have 1 column" );
		}
		final Selectable selectable = indexValue.getColumnIterator().next();
		if ( selectable.isFormula() ) {
			throw new AssertionFailure( "Map key mapped by @MapKeyColumn is a Formula" );
		}
		Column column = (Column) map.getIndex().getColumnIterator().next();
		if ( !column.isNullable() ) {
			final PersistentClass persistentClass = ( ( OneToMany ) map.getElement() ).getAssociatedClass();
			// check if the index column has been mapped by the associated entity to a property;
			// @MapKeyColumn only maps a column to the primary table for the one-to-many, so we only
			// need to check "un-joined" properties.
			if ( !propertyIteratorContainsColumn( persistentClass.getUnjoinedPropertyIterator(), column ) ) {
				// The index column is not mapped to an associated entity property so we can
				// safely make the index column nullable.
				column.setNullable( true );
			}
		}
	}
}
 
Example #16
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static boolean applyNotNull(Property property, ConstraintDescriptor<?> descriptor) {
	boolean hasNotNull = false;
	if ( NotNull.class.equals( descriptor.getAnnotation().annotationType() ) ) {
		// single table inheritance should not be forced to null due to shared state
		if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) {
			//composite should not add not-null on all columns
			if ( !property.isComposite() ) {
				final Iterator<Selectable> itr = property.getColumnIterator();
				while ( itr.hasNext() ) {
					final Selectable selectable = itr.next();
					if ( Column.class.isInstance( selectable ) ) {
						Column.class.cast( selectable ).setNullable( false );
					}
					else {
						LOG.debugf(
								"@NotNull was applied to attribute [%s] which is defined (at least partially) " +
										"by formula(s); formula portions will be skipped",
								property.getName()
						);
					}
				}
			}
		}
		hasNotNull = true;
	}
	return hasNotNull;
}
 
Example #17
Source File: ExportableColumn.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Iterator<Selectable> getColumnIterator() {
	return new ColumnIterator( column );
}
 
Example #18
Source File: ModelBinder.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void bindProperty(
		MappingDocument mappingDocument,
		AttributeSource propertySource,
		Property property) {
	property.setName( propertySource.getName() );

	if ( StringHelper.isNotEmpty( propertySource.getXmlNodeName() ) ) {
		DeprecationLogger.DEPRECATION_LOGGER.logDeprecationOfDomEntityModeSupport();
	}

	property.setPropertyAccessorName(
			StringHelper.isNotEmpty( propertySource.getPropertyAccessorName() )
					? propertySource.getPropertyAccessorName()
					: mappingDocument.getMappingDefaults().getImplicitPropertyAccessorName()
	);

	if ( propertySource instanceof CascadeStyleSource ) {
		final CascadeStyleSource cascadeStyleSource = (CascadeStyleSource) propertySource;

		property.setCascade(
				StringHelper.isNotEmpty( cascadeStyleSource.getCascadeStyleName() )
						? cascadeStyleSource.getCascadeStyleName()
						: mappingDocument.getMappingDefaults().getImplicitCascadeStyleName()
		);
	}

	property.setOptimisticLocked( propertySource.isIncludedInOptimisticLocking() );

	if ( propertySource.isSingular() ) {
		final SingularAttributeSource singularAttributeSource = (SingularAttributeSource) propertySource;

		property.setInsertable( singularAttributeSource.isInsertable() );
		property.setUpdateable( singularAttributeSource.isUpdatable() );

		// NOTE : Property#is refers to whether a property is lazy via bytecode enhancement (not proxies)
		property.setLazy( singularAttributeSource.isBytecodeLazy() );

		final GenerationTiming generationTiming = singularAttributeSource.getGenerationTiming();
		if ( generationTiming == GenerationTiming.ALWAYS || generationTiming == GenerationTiming.INSERT ) {
			// we had generation specified...
			//   	HBM only supports "database generated values"
			property.setValueGenerationStrategy( new GeneratedValueGeneration( generationTiming ) );

			// generated properties can *never* be insertable...
			if ( property.isInsertable() ) {
				log.debugf(
						"Property [%s] specified %s generation, setting insertable to false : %s",
						propertySource.getName(),
						generationTiming.name(),
						mappingDocument.getOrigin()
				);
				property.setInsertable( false );
			}

			// properties generated on update can never be updatable...
			if ( property.isUpdateable() && generationTiming == GenerationTiming.ALWAYS ) {
				log.debugf(
						"Property [%s] specified ALWAYS generation, setting updateable to false : %s",
						propertySource.getName(),
						mappingDocument.getOrigin()
				);
				property.setUpdateable( false );
			}
		}
	}

	property.setMetaAttributes( propertySource.getToolingHintContext().getMetaAttributeMap() );

	if ( log.isDebugEnabled() ) {
		final StringBuilder message = new StringBuilder()
				.append( "Mapped property: " )
				.append( propertySource.getName() )
				.append( " -> [" );
		final Iterator itr = property.getValue().getColumnIterator();
		while ( itr.hasNext() ) {
			message.append( ( (Selectable) itr.next() ).getText() );
			if ( itr.hasNext() ) {
				message.append( ", " );
			}
		}
		message.append( "]" );
		log.debug( message.toString() );
	}
}
 
Example #19
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Called for Maps
 */
public static void bindMapSecondPass(Element node, Map map, java.util.Map classes,
		Mappings mappings, java.util.Map inheritedMetas) throws MappingException {

	bindCollectionSecondPass( node, map, classes, mappings, inheritedMetas );

	Iterator iter = node.elementIterator();
	while ( iter.hasNext() ) {
		Element subnode = (Element) iter.next();
		String name = subnode.getName();

		if ( "index".equals( name ) || "map-key".equals( name ) ) {
			SimpleValue value = new SimpleValue( map.getCollectionTable() );
			bindSimpleValue(
					subnode,
					value,
					map.isOneToMany(),
					IndexedCollection.DEFAULT_INDEX_COLUMN_NAME,
					mappings
				);
			if ( !value.isTypeSpecified() ) {
				throw new MappingException( "map index element must specify a type: "
					+ map.getRole() );
			}
			map.setIndex( value );
			map.setIndexNodeName( subnode.attributeValue("node") );
		}
		else if ( "index-many-to-many".equals( name ) || "map-key-many-to-many".equals( name ) ) {
			ManyToOne mto = new ManyToOne( map.getCollectionTable() );
			bindManyToOne(
					subnode,
					mto,
					IndexedCollection.DEFAULT_INDEX_COLUMN_NAME,
					map.isOneToMany(),
					mappings
				);
			map.setIndex( mto );

		}
		else if ( "composite-index".equals( name ) || "composite-map-key".equals( name ) ) {
			Component component = new Component( map );
			bindComposite(
					subnode,
					component,
					map.getRole() + ".index",
					map.isOneToMany(),
					mappings,
					inheritedMetas
				);
			map.setIndex( component );
		}
		else if ( "index-many-to-any".equals( name ) ) {
			Any any = new Any( map.getCollectionTable() );
			bindAny( subnode, any, map.isOneToMany(), mappings );
			map.setIndex( any );
		}
	}

	// TODO: this is a bit of copy/paste from IndexedCollection.createPrimaryKey()
	boolean indexIsFormula = false;
	Iterator colIter = map.getIndex().getColumnIterator();
	while ( colIter.hasNext() ) {
		if ( ( (Selectable) colIter.next() ).isFormula() ) indexIsFormula = true;
	}

	if ( map.isOneToMany() && !map.getKey().isNullable() && !map.isInverse() && !indexIsFormula ) {
		String entityName = ( (OneToMany) map.getElement() ).getReferencedEntityName();
		PersistentClass referenced = mappings.getClass( entityName );
		IndexBackref ib = new IndexBackref();
		ib.setName( '_' + node.attributeValue( "name" ) + "IndexBackref" );
		ib.setUpdateable( false );
		ib.setSelectable( false );
		ib.setCollectionRole( map.getRole() );
		ib.setEntityName( map.getOwner().getEntityName() );
		ib.setValue( map.getIndex() );
		// ( (Column) ( (SimpleValue) ic.getIndex() ).getColumnIterator().next()
		// ).setNullable(false);
		referenced.addProperty( ib );
	}
}