org.hibernate.MappingException Java Examples

The following examples show how to use org.hibernate.MappingException. 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: BasicCollectionJoinWalker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public BasicCollectionJoinWalker(
		QueryableCollection collectionPersister, 
		int batchSize, 
		String subquery, 
		SessionFactoryImplementor factory, 
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {

	super( factory, loadQueryInfluencers );

	this.collectionPersister = collectionPersister;

	String alias = generateRootAlias( collectionPersister.getRole() );

	walkCollectionTree(collectionPersister, alias);

	List allAssociations = new ArrayList();
	allAssociations.addAll(associations);
	allAssociations.add( OuterJoinableAssociation.createRoot( collectionPersister.getCollectionType(), alias, getFactory() ) );
	initPersisters(allAssociations, LockMode.NONE);
	initStatementString(alias, batchSize, subquery);
}
 
Example #2
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private CompletionStage<Void> fireMerge(MergeContext copiedAlready, MergeEvent event) {
	pulseTransactionCoordinator();

	return fire(event, copiedAlready, EventType.MERGE,
			(ReactiveMergeEventListener l) -> l::reactiveOnMerge)
			.handle( (v,e) -> {
				delayedAfterCompletion();

				if (e instanceof ObjectDeletedException) {
					throw getExceptionConverter().convert( new IllegalArgumentException( e ) );
				}
				else if (e instanceof MappingException) {
					throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
				}
				else if (e instanceof RuntimeException) {
					//including HibernateException
					throw getExceptionConverter().convert( (RuntimeException) e );
				}
				return CompletionStages.returnNullorRethrow( e );
			});

}
 
Example #3
Source File: CollectionType.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public String getAssociatedEntityName(SessionFactoryImplementor factory)
		throws MappingException {
	try {

		QueryableCollection collectionPersister = (QueryableCollection) factory
				.getCollectionPersister( role );

		if ( !collectionPersister.getElementType().isEntityType() ) {
			throw new MappingException(
					"collection was not an association: " +
					collectionPersister.getRole()
			);
		}

		return collectionPersister.getElementPersister().getEntityName();

	}
	catch (ClassCastException cce) {
		throw new MappingException( "collection role is not queryable " + role );
	}
}
 
Example #4
Source File: QueryPlanCache.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get the query plan for the given collection HQL filter fragment, creating it and caching it if not already cached
 *
 * @param filterString The HQL filter fragment
 * @param collectionRole The collection being filtered
 * @param shallow Whether the execution will be shallow
 * @param enabledFilters The filters enabled on the Session
 *
 * @return The query plan
 *
 * @throws QueryException Indicates a problem translating the query
 * @throws MappingException Indicates a problem translating the query
 */
@SuppressWarnings("unchecked")
public FilterQueryPlan getFilterQueryPlan(
		String filterString,
		String collectionRole,
		boolean shallow,
		Map<String,Filter> enabledFilters) throws QueryException, MappingException {
	final FilterQueryPlanKey key =  new FilterQueryPlanKey( filterString, collectionRole, shallow, enabledFilters );
	FilterQueryPlan value = (FilterQueryPlan) queryPlanCache.get( key );
	if ( value == null ) {
		LOG.tracev(
				"Unable to locate collection-filter query plan in cache; generating ({0} : {1} )",
				collectionRole,
				filterString
		);
		value = new FilterQueryPlan( filterString, collectionRole, shallow, enabledFilters,factory );
		queryPlanCache.putIfAbsent( key, value );
	}
	else {
		LOG.tracev( "Located collection-filter query plan in cache ({0} : {1})", collectionRole, filterString );
	}
	return value;
}
 
Example #5
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private CompletionStage<Void> fireRemove(DeleteEvent event, IdentitySet transientEntities) {
	pulseTransactionCoordinator();

	return fire(event, transientEntities, EventType.DELETE,
			(ReactiveDeleteEventListener l) -> l::reactiveOnDelete)
			.handle( (v, e) -> {
				delayedAfterCompletion();

				if ( e instanceof ObjectDeletedException ) {
					throw getExceptionConverter().convert( new IllegalArgumentException( e ) );
				}
				else if ( e instanceof MappingException ) {
					throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage(), e ) );
				}
				else if ( e instanceof RuntimeException ) {
					//including HibernateException
					throw getExceptionConverter().convert( (RuntimeException) e );
				}
				return CompletionStages.returnNullorRethrow( e );
			});
}
 
Example #6
Source File: BasicCollectionLoader.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected BasicCollectionLoader(
		QueryableCollection collectionPersister,
		int batchSize,
		String subquery,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super( collectionPersister, factory, loadQueryInfluencers );

	JoinWalker walker = new BasicCollectionJoinWalker(
			collectionPersister,
			batchSize,
			subquery,
			factory,
			loadQueryInfluencers
	);
	initFromWalker( walker );

	postInstantiate();

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "Static select for collection %s: %s", collectionPersister.getRole(), getSQLString() );
	}
}
 
Example #7
Source File: SerializableToBlobType.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void setParameterValues(Properties parameters) {
	ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE );
	if ( reader != null ) {
		setJavaTypeDescriptor( new SerializableTypeDescriptor<T>( reader.getReturnedClass() ) );
	}
	else {
		String className = parameters.getProperty( CLASS_NAME );
		if ( className == null ) {
			throw new MappingException( "No class name defined for type: " + SerializableToBlobType.class.getName() );
		}
		try {
			setJavaTypeDescriptor( new SerializableTypeDescriptor<T>( ReflectHelper.classForName( className ) ) );
		}
		catch ( ClassNotFoundException e ) {
			throw new MappingException( "Unable to load class from " + CLASS_NAME + " parameter", e );
		}
	}
}
 
Example #8
Source File: ReactiveSessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
private CompletionStage<Void> firePersist(IdentitySet copiedAlready, PersistEvent event) {
	pulseTransactionCoordinator();

	return fire(event, copiedAlready, EventType.PERSIST,
			(ReactivePersistEventListener l) -> l::reactiveOnPersist)
			.handle( (v, e) -> {
				delayedAfterCompletion();

				if (e instanceof MappingException) {
					throw getExceptionConverter().convert( new IllegalArgumentException( e.getMessage() ) );
				}
				else if (e instanceof RuntimeException) {
					throw getExceptionConverter().convert( (RuntimeException) e );
				}
				return CompletionStages.returnNullorRethrow( e );
			});
}
 
Example #9
Source File: ForeignKey.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void alignColumns(Table referencedTable) {
	final int referencedPkColumnSpan = referencedTable.getPrimaryKey().getColumnSpan();
	if ( referencedPkColumnSpan != getColumnSpan() ) {
		StringBuilder sb = new StringBuilder();
		sb.append( "Foreign key (" ).append( getName() ).append( ":" )
				.append( getTable().getName() )
				.append( " [" );
		appendColumns( sb, getColumnIterator() );
		sb.append( "])" )
				.append( ") must have same number of columns as the referenced primary key (" )
				.append( referencedTable.getName() )
				.append( " [" );
		appendColumns( sb, referencedTable.getPrimaryKey().getColumnIterator() );
		sb.append( "])" );
		throw new MappingException( sb.toString() );
	}

	Iterator fkCols = getColumnIterator();
	Iterator pkCols = referencedTable.getPrimaryKey().getColumnIterator();
	while ( pkCols.hasNext() ) {
		( (Column) fkCols.next() ).setLength( ( (Column) pkCols.next() ).getLength() );
	}

}
 
Example #10
Source File: PersistentClass.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected void checkColumnDuplication(Set distinctColumns, Iterator columns)
		throws MappingException {
	while ( columns.hasNext() ) {
		Selectable columnOrFormula = (Selectable) columns.next();
		if ( !columnOrFormula.isFormula() ) {
			Column col = (Column) columnOrFormula;
			if ( !distinctColumns.add( col.getName() ) ) {
				throw new MappingException(
						"Repeated column in mapping for entity: " +
								getEntityName() +
								" column: " +
								col.getName() +
								" (should be mapped with insert=\"false\" update=\"false\")"
				);
			}
		}
	}
}
 
Example #11
Source File: HibernateFactory.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return the persistent instance of the given entity class with the given
 * identifier, or null if there is no such persistent instance. (If the
 * instance, or a proxy for the instance, is already associated with the
 * session, return that instance or proxy.)
 * @param clazz a persistent class
 * @param id an identifier
 * @return Object persistent instance or null
 */
public Object getObject(Class clazz, Serializable id) {
    Object retval = null;
    Session session = null;

    try {
        session = HibernateFactory.getSession();

        retval = session.get(clazz, id);
    }
    catch (MappingException me) {
        getLogger().error("Mapping not found for " + clazz.getName(), me);

    }
    catch (HibernateException he) {
        getLogger().error("Hibernate exception: " + he.toString());
    }

    return retval;
}
 
Example #12
Source File: DefaultIdentifierGeneratorFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Class getIdentifierGeneratorClass(String strategy) {
	if ( "hilo".equals( strategy ) ) {
		throw new UnsupportedOperationException( "Support for 'hilo' generator has been removed" );
	}
	String resolvedStrategy = "native".equals( strategy ) ?
			getDialect().getNativeIdentifierGeneratorStrategy() : strategy;

	Class generatorClass = generatorStrategyToClassNameMap.get( resolvedStrategy );
	try {
		if ( generatorClass == null ) {
			final ClassLoaderService cls = serviceRegistry.getService( ClassLoaderService.class );
			generatorClass = cls.classForName( resolvedStrategy );
		}
	}
	catch ( ClassLoadingException e ) {
		throw new MappingException( String.format( "Could not interpret id generator strategy [%s]", strategy ) );
	}
	return generatorClass;
}
 
Example #13
Source File: AbstractEntityTuplizer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private int findSubPropertyIndex(ComponentType type, String subPropertyName) {
	final String[] propertyNames = type.getPropertyNames();
	for ( int index = 0; index < propertyNames.length; index++ ) {
		if ( subPropertyName.equals( propertyNames[index] ) ) {
			return index;
		}
	}
	throw new MappingException( "component property not found: " + subPropertyName );
}
 
Example #14
Source File: JoinSequence.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
Join(
		SessionFactoryImplementor factory,
		AssociationType associationType,
		String alias,
		JoinType joinType,
		String[][] lhsColumns) throws MappingException {
	this.associationType = associationType;
	this.joinable = associationType.getAssociatedJoinable( factory );
	this.alias = alias;
	this.joinType = joinType;
	this.lhsColumns = lhsColumns;
}
 
Example #15
Source File: IndexCreator.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
private SessionFactory createSessionFactory(String url, String login, String passwd, String dialect, String driverClass, String mappedClasses) throws MappingException, ClassNotFoundException {
	Configuration cfg = new Configuration();
	for (String className:mappedClasses.split(",")) {
		cfg.addClass(Class.forName(className));
	}
	cfg.setProperty("hibernate.current_session_context_class", "thread");
	cfg.setProperty("hibernate.transaction.factory_class","org.hibernate.transaction.JDBCTransactionFactory");
	cfg.setProperty("hibernate.connection.driver_class", driverClass);
	cfg.setProperty("hibernate.connection.password", passwd);
	cfg.setProperty("hibernate.connection.username", login);
	cfg.setProperty("hibernate.default_schema", "PUBLIC");
	cfg.setProperty("hibernate.connection.url", url);
	return  cfg.buildSessionFactory();
}
 
Example #16
Source File: BasicCollectionJoinWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected JoinType getJoinType(
		OuterJoinLoadable persister,
		PropertyPath path,
		int propertyNumber,
		AssociationType associationType,
		FetchMode metadataFetchMode,
		CascadeStyle metadataCascadeStyle,
		String lhsTable,
		String[] lhsColumns,
		boolean nullable,
		int currentDepth) throws MappingException {
	JoinType joinType = super.getJoinType(
			persister,
			path,
			propertyNumber,
			associationType,
			metadataFetchMode,
			metadataCascadeStyle,
			lhsTable,
			lhsColumns,
			nullable,
			currentDepth
	);
	//we can use an inner join for the many-to-many
	if ( joinType==JoinType.LEFT_OUTER_JOIN && path.isRoot() ) {
		joinType=JoinType.INNER_JOIN;
	}
	return joinType;
}
 
Example #17
Source File: EntityBinder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public AccessType getExplicitAccessType(XAnnotatedElement element) {
	AccessType accessType = null;

	AccessType hibernateAccessType = null;
	AccessType jpaAccessType = null;

	org.hibernate.annotations.AccessType accessTypeAnnotation = element.getAnnotation( org.hibernate.annotations.AccessType.class );
	if ( accessTypeAnnotation != null ) {
		hibernateAccessType = AccessType.getAccessStrategy( accessTypeAnnotation.value() );
	}

	Access access = element.getAnnotation( Access.class );
	if ( access != null ) {
		jpaAccessType = AccessType.getAccessStrategy( access.value() );
	}

	if ( hibernateAccessType != null && jpaAccessType != null && hibernateAccessType != jpaAccessType ) {
		throw new MappingException(
				"Found @Access and @AccessType with conflicting values on a property in class " + annotatedClass.toString()
		);
	}

	if ( hibernateAccessType != null ) {
		accessType = hibernateAccessType;
	}
	else if ( jpaAccessType != null ) {
		accessType = jpaAccessType;
	}

	return accessType;
}
 
Example #18
Source File: ComponentType.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Size[] dictatedSizes(Mapping mapping) throws MappingException {
	//Not called at runtime so doesn't matter if its slow :)
	final Size[] sizes = new Size[getColumnSpan( mapping )];
	int soFar = 0;
	for ( Type propertyType : propertyTypes ) {
		final Size[] propertySizes = propertyType.dictatedSizes( mapping );
		System.arraycopy( propertySizes, 0, sizes, soFar, propertySizes.length );
		soFar += propertySizes.length;
	}
	return sizes;
}
 
Example #19
Source File: AbstractCollectionPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String filterFragment(String alias, Map enabledFilters) throws MappingException {
	StringBuilder sessionFilterFragment = new StringBuilder();
	filterHelper.render( sessionFilterFragment, getFilterAliasGenerator(alias), enabledFilters );

	return sessionFilterFragment.append( filterFragment( alias ) ).toString();
}
 
Example #20
Source File: Table.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public Index addIndex(Index index) {
	Index current = (Index) indexes.get( index.getName() );
	if ( current != null ) {
		throw new MappingException( "Index " + index.getName() + " already exists!" );
	}
	indexes.put( index.getName(), index );
	return index;
}
 
Example #21
Source File: StandardAnsiSqlAggregationFunctions.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected final int determineJdbcTypeCode(Type firstArgumentType, SessionFactoryImplementor factory) throws QueryException {
	try {
		final int[] jdbcTypeCodes = firstArgumentType.sqlTypes( factory );
		if ( jdbcTypeCodes.length != 1 ) {
			throw new QueryException( "multiple-column type in avg()" );
		}
		return jdbcTypeCodes[0];
	}
	catch ( MappingException me ) {
		throw new QueryException( me );
	}
}
 
Example #22
Source File: SingleTableEntityPersister.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void addSubclassByDiscriminatorValue(Object discriminatorValue, String entityName) {
	String mappedEntityName = subclassesByDiscriminatorValue.put( discriminatorValue, entityName );
	if ( mappedEntityName != null ) {
		throw new MappingException(
				"Entities [" + entityName + "] and [" + mappedEntityName
						+ "] are mapped with the same discriminator value '" + discriminatorValue + "'."
		);
	}
}
 
Example #23
Source File: SequenceStyleGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void configure(Type type, Properties params, ServiceRegistry serviceRegistry) throws MappingException {
	final JdbcEnvironment jdbcEnvironment = serviceRegistry.getService( JdbcEnvironment.class );
	final Dialect dialect = jdbcEnvironment.getDialect();

	this.identifierType = type;
	boolean forceTableUse = ConfigurationHelper.getBoolean( FORCE_TBL_PARAM, params, false );

	final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment, serviceRegistry );

	final int initialValue = determineInitialValue( params );
	int incrementSize = determineIncrementSize( params );

	final String optimizationStrategy = determineOptimizationStrategy( params, incrementSize );
	incrementSize = determineAdjustedIncrementSize( optimizationStrategy, incrementSize );

	if ( dialect.supportsSequences() && !forceTableUse ) {
		if ( !dialect.supportsPooledSequences() && OptimizerFactory.isPooledOptimizer( optimizationStrategy ) ) {
			forceTableUse = true;
			LOG.forcingTableUse();
		}
	}

	this.databaseStructure = buildDatabaseStructure(
			type,
			params,
			jdbcEnvironment,
			forceTableUse,
			sequenceName,
			initialValue,
			incrementSize
	);
	this.optimizer = OptimizerFactory.buildOptimizer(
			optimizationStrategy,
			identifierType.getReturnedClass(),
			incrementSize,
			ConfigurationHelper.getInt( INITIAL_PARAM, params, -1 )
	);
	this.databaseStructure.prepare( optimizer );
}
 
Example #24
Source File: InFlightMetadataCollectorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getIdentifierPropertyName(String entityName) throws MappingException {
	final PersistentClass pc = entityBindingMap.get( entityName );
	if ( pc == null ) {
		throw new MappingException( "persistent class not known: " + entityName );
	}
	if ( !pc.hasIdentifierProperty() ) {
		return null;
	}
	return pc.getIdentifierProperty().getName();
}
 
Example #25
Source File: TypeFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static void injectParameters(Object type, Properties parameters) {
	if ( ParameterizedType.class.isInstance( type ) ) {
		if ( parameters == null ) {
			( (ParameterizedType) type ).setParameterValues( EMPTY_PROPERTIES );
		}
		else {
			( (ParameterizedType) type ).setParameterValues( parameters );
		}
	}
	else if ( parameters != null && !parameters.isEmpty() ) {
		throw new MappingException( "type is not parameterized: " + type.getClass().getName() );
	}
}
 
Example #26
Source File: NativeQueryImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a NativeQueryImpl given a sql query defined in the mappings.
 *
 * @param queryDef The representation of the defined <sql-query/>.
 * @param session The session to which this NativeQuery belongs.
 * @param parameterMetadata Metadata about parameters found in the query.
 */
public NativeQueryImpl(
		NamedSQLQueryDefinition queryDef,
		SharedSessionContractImplementor session,
		ParameterMetadata parameterMetadata) {
	super( session, parameterMetadata );

	this.sqlString = queryDef.getQueryString();
	this.callable = queryDef.isCallable();
	this.querySpaces = queryDef.getQuerySpaces() == null ? null : new ArrayList<>( queryDef.getQuerySpaces() );

	if ( queryDef.getResultSetRef() != null ) {
		ResultSetMappingDefinition definition = session.getFactory()
				.getNamedQueryRepository()
				.getResultSetMappingDefinition( queryDef.getResultSetRef() );
		if ( definition == null ) {
			throw new MappingException(
					"Unable to find resultset-ref definition: " +
							queryDef.getResultSetRef()
			);
		}
		this.queryReturns = new ArrayList<>( Arrays.asList( definition.getQueryReturns() ) );
	}
	else if ( queryDef.getQueryReturns() != null && queryDef.getQueryReturns().length > 0 ) {
		this.queryReturns = new ArrayList<>( Arrays.asList( queryDef.getQueryReturns() ) );
	}
	else {
		this.queryReturns = new ArrayList<>();
	}


	this.queryParameterBindings = QueryParameterBindingsImpl.from(
			parameterMetadata,
			session.getFactory(),
			session.isQueryParametersValidationEnabled()
	);
}
 
Example #27
Source File: JoinSequence.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
Join(AssociationType associationType, String alias, int joinType, String[] lhsColumns)
		throws MappingException {
	this.associationType = associationType;
	this.joinable = associationType.getAssociatedJoinable( factory );
	this.alias = alias;
	this.joinType = joinType;
	this.lhsColumns = lhsColumns;
}
 
Example #28
Source File: QueryTranslatorImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compile a "normal" query. This method may be called multiple
 * times. Subsequent invocations are no-ops.
 */
public synchronized void compile(
		Map replacements,
		boolean scalar) throws QueryException, MappingException {
	if ( !compiled ) {
		this.tokenReplacements = replacements;
		this.shallowQuery = scalar;
		compile();
	}
}
 
Example #29
Source File: DerbyDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getSequenceNextValString(String sequenceName) {
	if ( supportsSequences() ) {
		return "values next value for " + sequenceName;
	}
	else {
		throw new MappingException( "Derby does not support sequence prior to release 10.6.1.0" );
	}
}
 
Example #30
Source File: Set.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public void validate(Mapping mapping) throws MappingException {
	super.validate( mapping );
	//for backward compatibility, disable this:
	/*Iterator iter = getElement().getColumnIterator();
	while ( iter.hasNext() ) {
		Column col = (Column) iter.next();
		if ( !col.isNullable() ) {
			return;
		}
	}
	throw new MappingException("set element mappings must have at least one non-nullable column: " + getRole() );*/
}