@Override @SuppressWarnings({"deprecation", "unchecked"}) public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException { final Type indexType = persister.getIndexType(); final HashMap snapshot = (HashMap) getSnapshot(); final HashMap deletes = (HashMap) snapshot.clone(); deletes.keySet().removeAll( ( (HashMap) getSnapshot( persister ) ).keySet() ); final ArrayList deleteList = new ArrayList( deletes.size() ); for ( Object o : deletes.entrySet() ) { final Map.Entry me = (Map.Entry) o; final Object object = indexIsFormula ? me.getValue() : ( (XmlRepresentableType) indexType ).fromXMLString( (String) me.getKey(), persister.getFactory() ); if ( object != null ) { deleteList.add( object ); } } return deleteList.iterator(); }
/** * Cascade an action to a to-one association or any type */ private void cascadeToOne( final Object parent, final Object child, final Type type, final CascadeStyle style, final Object anything, final boolean isCascadeDeleteEnabled) { final String entityName = type.isEntityType() ? ( (EntityType) type ).getAssociatedEntityName() : null; if ( style.reallyDoCascade( action ) ) { //not really necessary, but good for consistency... eventSource.getPersistenceContext().addChildParent( child, parent ); try { action.cascade( eventSource, child, entityName, anything, isCascadeDeleteEnabled ); } finally { eventSource.getPersistenceContext().removeChildParent( child ); } } }
@Override protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session) throws SQLException, HibernateException { final Object[] result; if ( translator.hasProjection() ) { Type[] types = translator.getProjectedTypes(); result = new Object[types.length]; String[] columnAliases = translator.getProjectedColumnAliases(); for ( int i=0, pos=0; i<result.length; i++ ) { int numColumns = types[i].getColumnSpan( session.getFactory() ); if ( numColumns > 1 ) { String[] typeColumnAliases = ArrayHelper.slice( columnAliases, pos, numColumns ); result[i] = types[i].nullSafeGet(rs, typeColumnAliases, session, null); } else { result[i] = types[i].nullSafeGet(rs, columnAliases[pos], session, null); } pos += numColumns; } } else { result = toResultRow( row ); } return result; }
private void initCollectionPropertyMap(String aliasName, Type type, String[] columnAliases, String[] columnNames) { collectionPropertyColumnAliases.put( aliasName, columnAliases ); collectionPropertyColumnNames.put( aliasName, columnNames ); if ( type.isComponentType() ) { CompositeType ct = (CompositeType) type; String[] propertyNames = ct.getPropertyNames(); for ( int i = 0; i < propertyNames.length; i++ ) { String name = propertyNames[i]; collectionPropertyColumnAliases.put( aliasName + "." + name, columnAliases[i] ); collectionPropertyColumnNames.put( aliasName + "." + name, columnNames[i] ); } } }
@Override @SuppressWarnings("deprecation") public Serializable disassemble(CollectionPersister persister) throws HibernateException { final Type elementType = persister.getElementType(); final String indexNodeName = getIndexAttributeName( persister ); final List elements = element.elements( persister.getElementNodeName() ); final int length = elements.size(); final Serializable[] result = new Serializable[length]; for ( int i=0; i<length; i++ ) { final Element elem = (Element) elements.get( i ); final Object object = elementType.fromXMLNode( elem, persister.getFactory() ); final Integer index = IntegerType.INSTANCE.fromString( getIndex( elem, indexNodeName, i ) ); result[index] = elementType.disassemble( object, getSession(), null ); } return result; }
@Override @SuppressWarnings("deprecation") public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException { final Type elementType = persister.getElementType(); final ArrayList snapshot = (ArrayList) getSnapshot(); final List elements = element.elements( persister.getElementNodeName() ); if ( snapshot.size() != elements.size() ) { return false; } for ( int i=0; i<snapshot.size(); i++ ) { final Object old = snapshot.get( i ); final Element elem = (Element) elements.get( i ); final Object current = elementType.fromXMLNode( elem, persister.getFactory() ); if ( elementType.isDirty( old, current, getSession() ) ) { return false; } } return true; }
/** * Find all non-nullable references to entities that have not yet * been inserted in the database, where the foreign key * is a reference to an unsaved transient entity. . * * @param entityName - the entity name * @param entity - the entity instance * @param values - insertable properties of the object (including backrefs), * possibly with substitutions * @param isEarlyInsert - true if the entity needs to be executed as soon as possible * (e.g., to generate an ID) * @param session - the session * * @return the transient unsaved entity dependencies that are non-nullable, * or null if there are none. */ public static NonNullableTransientDependencies findNonNullableTransientEntities( String entityName, Object entity, Object[] values, boolean isEarlyInsert, SessionImplementor session) { final Nullifier nullifier = new Nullifier( entity, false, isEarlyInsert, session ); final EntityPersister persister = session.getEntityPersister( entityName, entity ); final String[] propertyNames = persister.getPropertyNames(); final Type[] types = persister.getPropertyTypes(); final boolean[] nullability = persister.getPropertyNullability(); final NonNullableTransientDependencies nonNullableTransientEntities = new NonNullableTransientDependencies(); for ( int i = 0; i < types.length; i++ ) { collectNonNullableTransientEntities( nullifier, values[i], propertyNames[i], types[i], nullability[i], session, nonNullableTransientEntities ); } return nonNullableTransientEntities.isEmpty() ? null : nonNullableTransientEntities; }
@Override @SuppressWarnings("deprecation") public Object readFrom(ResultSet rs, CollectionPersister persister, CollectionAliases descriptor, Object owner) throws HibernateException, SQLException { final Object object = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() ); final Type elementType = persister.getElementType(); final Element subElement = element.addElement( persister.getElementNodeName() ); elementType.setToXMLNode( subElement, object, persister.getFactory() ); return object; }
private Type resolveDateTimeArithmeticResultType(Type lhType, Type rhType) { // here, we work under the following assumptions: // ------------ valid cases -------------------------------------- // 1) datetime + {something other than datetime} : always results // in a datetime ( db will catch invalid conversions ) // 2) datetime - datetime : always results in a DOUBLE // 3) datetime - {something other than datetime} : always results // in a datetime ( db will catch invalid conversions ) // ------------ invalid cases ------------------------------------ // 4) datetime + datetime // 5) {something other than datetime} - datetime // 6) datetime * {any type} // 7) datetime / {any type} // 8) {any type} / datetime // doing so allows us to properly handle parameters as either the left // or right side here in the majority of cases boolean lhsIsDateTime = isDateTimeType( lhType ); boolean rhsIsDateTime = isDateTimeType( rhType ); // handle the (assumed) valid cases: // #1 - the only valid datetime addition synatx is one or the other is a datetime (but not both) if ( getType() == HqlSqlTokenTypes.PLUS ) { // one or the other needs to be a datetime for us to get into this method in the first place... return lhsIsDateTime ? lhType : rhType; } else if ( getType() == HqlSqlTokenTypes.MINUS ) { // #3 - note that this is also true of "datetime - :param"... if ( lhsIsDateTime && !rhsIsDateTime ) { return lhType; } // #2 if ( lhsIsDateTime && rhsIsDateTime ) { return StandardBasicTypes.DOUBLE; } } return null; }
@Override public Query setParameterList(String name, Collection vals, Type type) throws HibernateException { if ( !parameterMetadata.getNamedParameterNames().contains( name ) ) { throw new IllegalArgumentException("Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]"); } namedParameterLists.put( name, new TypedValue( type, vals ) ); return this; }
@Override public Type getDataType() { if ( super.getDataType() == null ) { FromElement fromElement = getLhs().getFromElement(); if ( fromElement == null ) { return null; } // If the lhs is a collection, use CollectionPropertyMapping Type propertyType = fromElement.getPropertyType( propertyName, propertyPath ); LOG.debugf( "getDataType() : %s -> %s", propertyPath, propertyType ); super.setDataType( propertyType ); } return super.getDataType(); }
/** * Dispatch each property value to processValue(). * * @param values * @param types * @throws HibernateException */ void processValues(Object[] values, Type[] types) throws HibernateException { for ( int i=0; i<types.length; i++ ) { if ( includeProperty(values, i) ) { processValue( i, values, types ); } } }
private DiscriminatorMetadata buildTypeDiscriminatorMetadata() { return new DiscriminatorMetadata() { public String getSqlFragment(String sqlQualificationAlias) { return toColumns( sqlQualificationAlias, ENTITY_CLASS )[0]; } public Type getResolutionType() { return new DiscriminatorType( getDiscriminatorType(), AbstractEntityPersister.this ); } }; }
private Object[] createDeletedState(EntityPersister persister, Object[] currentState, EventSource session) { Type[] propTypes = persister.getPropertyTypes(); final Object[] deletedState = new Object[propTypes.length]; // TypeFactory.deepCopy( currentState, propTypes, persister.getPropertyUpdateability(), deletedState, session ); boolean[] copyability = new boolean[propTypes.length]; java.util.Arrays.fill( copyability, true ); TypeHelper.deepCopy( currentState, propTypes, copyability, deletedState, session ); return deletedState; }
public String toString(Type[] types, Object[] values) throws HibernateException { StringBuilder buffer = new StringBuilder(); for ( int i=0; i<types.length; i++ ) { if ( types[i]!=null ) { buffer.append( types[i].toLoggableString( values[i], factory ) ).append( ", " ); } } return buffer.toString(); }
public Type getType() throws MappingException { final Type metaType = getMappings().getTypeResolver().heuristicType( metaTypeName ); return getMappings().getTypeResolver().getTypeFactory().any( metaValues == null ? metaType : new MetaType( metaValues, metaType ), getMappings().getTypeResolver().heuristicType( identifierTypeName ) ); }
@Override public int[] findDirty( Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) { return null; }
private void processFilterDefinitions() { if ( mappingRoot().getFilterDef() == null ) { return; } for ( JaxbHibernateMapping.JaxbFilterDef filterDefinition : mappingRoot().getFilterDef() ) { final String name = filterDefinition.getName(); final Map<String,Type> parameters = new HashMap<String, Type>(); String condition = null; for ( Object o : filterDefinition.getContent() ) { if ( o instanceof String ) { // represents the condition if ( condition != null ) { // log? } condition = (String) o; } else if ( o instanceof JaxbHibernateMapping.JaxbFilterDef.JaxbFilterParam ) { final JaxbHibernateMapping.JaxbFilterDef.JaxbFilterParam paramElement = JaxbHibernateMapping.JaxbFilterDef.JaxbFilterParam.class.cast( o ); // todo : should really delay this resolution until later to allow typedef names parameters.put( paramElement.getName(), metadata.getTypeResolver().heuristicType( paramElement.getType() ) ); } else { throw new MappingException( "Unrecognized nested filter content", origin() ); } } if ( condition == null ) { condition = filterDefinition.getCondition(); } metadata.addFilterDefinition( new FilterDefinition( name, condition, parameters ) ); } }
private void resolveDiscriminatorTypeInformation(EntityDiscriminator discriminator) { // perform any needed type resolutions for discriminator Type resolvedHibernateType = determineSingularTypeFromDescriptor( discriminator.getExplicitHibernateTypeDescriptor() ); if ( resolvedHibernateType != null ) { pushHibernateTypeInformationDownIfNeeded( discriminator.getExplicitHibernateTypeDescriptor(), discriminator.getBoundValue(), resolvedHibernateType ); } }
public Type getDataType() { final AST expression = getFirstChild(); // option is used to hold each WHEN/ELSE in turn AST option = expression.getNextSibling(); while ( option != null ) { final AST result; if ( option.getType() == HqlSqlTokenTypes.WHEN ) { result = option.getFirstChild().getNextSibling(); } else if ( option.getType() == HqlSqlTokenTypes.ELSE ) { result = option.getFirstChild(); } else { throw new QueryException( "Unexpected node type :" + ASTUtil.getTokenTypeName( HqlSqlTokenTypes.class, option.getType() ) + "; expecting WHEN or ELSE" ); } if ( SqlNode.class.isInstance( result ) ) { final Type nodeDataType = ( (SqlNode) result ).getDataType(); if ( nodeDataType != null ) { return nodeDataType; } } option = option.getNextSibling(); } throw new QueryException( "Could not determine data type for simple case statement" ); }
private Type getHeuristicType(String typeName, Properties typeParameters) { if ( typeName != null ) { try { return metadata.getTypeResolver().heuristicType( typeName, typeParameters ); } catch (Exception ignore) { } } return null; }
public EntityUniqueKey( final String entityName, final String uniqueKeyName, final Object semiResolvedKey, final Type keyType, final EntityMode entityMode, final SessionFactoryImplementor factory) { this.uniqueKeyName = uniqueKeyName; this.entityName = entityName; this.key = semiResolvedKey; this.keyType = keyType.getSemiResolvedType( factory ); this.entityMode = entityMode; this.hashCode = generateHashCode( factory ); }
public QueryParameters( final Type[] positionalParameterTypes, final Object[] positionalParameterValues, final LockOptions lockOptions, final RowSelection rowSelection, final boolean isReadOnlyInitialized, final boolean readOnly, final boolean cacheable, final String cacheRegion, //final boolean forceCacheRefresh, final String comment, final List<String> queryHints, final boolean isLookupByNaturalKey, final ResultTransformer transformer) { this( positionalParameterTypes, positionalParameterValues, null, lockOptions, rowSelection, isReadOnlyInitialized, readOnly, cacheable, cacheRegion, comment, queryHints, null, transformer ); isNaturalKeyLookup = isLookupByNaturalKey; }
private void collectionProperty(AST path, AST name) throws SemanticException { if ( path == null ) { throw new SemanticException( "Collection function " + name.getText() + " has no path!" ); } SqlNode expr = (SqlNode) path; Type type = expr.getDataType(); LOG.debugf( "collectionProperty() : name=%s type=%s", name, type ); resolveCollectionProperty( expr ); }
@Override public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { boolean changed = false; for (PersistListener listener: listeners) { if (listener.onLoad(entity, id, state, propertyNames, types)) changed = true; } return changed; }
protected Type determineType(int paramPosition, Object paramValue, Type defaultType) { Type type = parameterMetadata.getOrdinalParameterExpectedType( paramPosition + 1 ); if ( type == null ) { type = defaultType; } return type; }
NamedParameterRegistration( ProcedureCallImpl procedureCall, String name, ParameterMode mode, Class<T> type, Type hibernateType) { super( procedureCall, name, mode, type, hibernateType ); }
@Override public void setHibernateType(Type type) { if ( type == null ) { throw new IllegalArgumentException( "Type cannot be null" ); } this.hibernateType = type; this.sqlTypes = hibernateType.sqlTypes( session().getFactory() ); }
public static String[][] generateColumnNames(Type[] types, SessionFactoryImplementor f) throws MappingException { String[][] columnNames = new String[types.length][]; for ( int i = 0; i < types.length; i++ ) { int span = types[i].getColumnSpan( f ); columnNames[i] = new String[span]; for ( int j = 0; j < span; j++ ) { columnNames[i][j] = NameGenerator.scalarName( i, j ); } } return columnNames; }
public Type findFunctionReturnType(String functionName, SQLFunction sqlFunction, AST firstArgument) { // determine the type of the first argument... Type argumentType = null; if ( firstArgument != null ) { if ( "cast".equals( functionName ) ) { argumentType = sfi.getTypeResolver().heuristicType( firstArgument.getNextSibling().getText() ); } else if ( SqlNode.class.isInstance( firstArgument ) ) { argumentType = ( (SqlNode) firstArgument ).getDataType(); } } return sqlFunction.getReturnType( argumentType, sfi ); }
private int countOccurrences(Object element, List list, Type elementType) throws HibernateException { final Iterator iter = list.iterator(); int result = 0; while ( iter.hasNext() ) { if ( elementType.isSame( element, iter.next() ) ) { result++; } } return result; }
protected AbstractEntityBasedAttribute( EntityPersister source, SessionFactoryImplementor sessionFactory, int attributeNumber, String attributeName, Type attributeType, BaselineAttributeInformation attributeInformation) { super( source, sessionFactory, attributeNumber, attributeName, attributeType, attributeInformation ); }
@Override @SuppressWarnings({"deprecation", "unchecked"}) public Iterator entries(CollectionPersister persister) { final Type elementType = persister.getElementType(); final List subElements = element.elements( persister.getElementNodeName() ); final int length = subElements.size(); final List result = new ArrayList(length); for ( Object subElementO : subElements ) { final Element subElement = (Element) subElementO; final Object object = elementType.fromXMLNode( subElement, persister.getFactory() ); result.add( object ); } return result.iterator(); }
/** * Renders an entity to a string. * * @param entityName the entity name * @param entity an actual entity object, not a proxy! * @return the entity rendered to a string */ public String toString(String entityName, Object entity) throws HibernateException { EntityPersister entityPersister = factory.getEntityPersister( entityName ); if ( entityPersister == null ) { return entity.getClass().getName(); } Map<String,String> result = new HashMap<String,String>(); if ( entityPersister.hasIdentifierProperty() ) { result.put( entityPersister.getIdentifierPropertyName(), entityPersister.getIdentifierType().toLoggableString( entityPersister.getIdentifier( entity ), factory ) ); } Type[] types = entityPersister.getPropertyTypes(); String[] names = entityPersister.getPropertyNames(); Object[] values = entityPersister.getPropertyValues( entity ); for ( int i=0; i<types.length; i++ ) { if ( !names[i].startsWith("_") ) { String strValue = values[i]==LazyPropertyInitializer.UNFETCHED_PROPERTY ? values[i].toString() : types[i].toLoggableString( values[i], factory ); result.put( names[i], strValue ); } } return entityName + result.toString(); }
private boolean indicatesCollection(Type type) { if ( type.isCollectionType() ) { return true; } else if ( type.isComponentType() ) { Type[] subtypes = ( (CompositeType) type ).getSubtypes(); for ( int i = 0; i < subtypes.length; i++ ) { if ( indicatesCollection( subtypes[i] ) ) { return true; } } } return false; }
protected AbstractParameterRegistrationImpl( ProcedureCallImpl procedureCall, String name, ParameterMode mode, Class<T> type, Type hibernateType) { this( procedureCall, null, name, mode, type, hibernateType ); }
/** * Check that the requested type is compatible with the result type, and * return the column value. This version makes sure the the classes * are "assignable". * * @param col the column * @param returnType any type */ protected final Object getNonFinal(int col, Type returnType) throws HibernateException { if ( holderInstantiator!=null ) { throw new HibernateException("query specifies a holder class"); } if ( returnType.getReturnedClass().isAssignableFrom( types[col].getReturnedClass() ) ) { return get(col); } else { return throwInvalidColumnTypeException(col, types[col], returnType); } }
@Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { final String[] columns = criteriaQuery.findColumns( propertyName, criteria ); final Type type = criteriaQuery.getTypeUsingProjection( criteria, propertyName ); final StringBuilder fragment = new StringBuilder(); if ( columns.length > 1 ) { fragment.append( '(' ); } final SessionFactoryImplementor factory = criteriaQuery.getFactory(); final int[] sqlTypes = type.sqlTypes( factory ); for ( int i = 0; i < columns.length; i++ ) { final boolean lower = ignoreCase && (sqlTypes[i] == Types.VARCHAR || sqlTypes[i] == Types.CHAR); if ( lower ) { fragment.append( factory.getDialect().getLowercaseFunction() ).append( '(' ); } fragment.append( columns[i] ); if ( lower ) { fragment.append( ')' ); } fragment.append( getOp() ).append( "?" ); if ( i < columns.length - 1 ) { fragment.append( " and " ); } } if ( columns.length > 1 ) { fragment.append( ')' ); } return fragment.toString(); }
@Override public void startingCollectionElements(CollectionElementDefinition elementDefinition) { final Type elementType = elementDefinition.getType(); log.tracef( "%s Starting collection element graph : %s", StringHelper.repeat( ">>", fetchSourceStack.size() ), elementDefinition.getCollectionDefinition().getCollectionPersister().getRole() ); final CollectionReference collectionReference = currentCollection(); final CollectionFetchableElement elementGraph = collectionReference.getElementGraph(); if ( elementType.isAssociationType() || elementType.isComponentType() ) { if ( elementGraph == null ) { throw new IllegalStateException( "CollectionReference did not return an expected element graph : " + elementDefinition.getCollectionDefinition().getCollectionPersister().getRole() ); } if ( !elementType.isAnyType() ) { pushToStack( (ExpandingFetchSource) elementGraph ); } } else { if ( elementGraph != null ) { throw new IllegalStateException( "CollectionReference returned an unexpected element graph : " + elementDefinition.getCollectionDefinition().getCollectionPersister().getRole() ); } } }
@Override public Type getTypeUsingProjection(Criteria subcriteria, String propertyName) throws HibernateException { //first look for a reference to a projection alias final Projection projection = rootCriteria.getProjection(); Type[] projectionTypes = projection == null ? null : projection.getTypes( propertyName, subcriteria, this ); if ( projectionTypes == null ) { try { //it does not refer to an alias of a projection, //look for a property return getType( subcriteria, propertyName ); } catch ( HibernateException he ) { //not found in inner query , try the outer query if ( outerQueryTranslator != null ) { return outerQueryTranslator.getType( subcriteria, propertyName ); } else { throw he; } } } else { if ( projectionTypes.length != 1 ) { //should never happen, i think throw new QueryException( "not a single-length projection: " + propertyName ); } return projectionTypes[0]; } }