Java Code Examples for org.hibernate.MappingException

The following examples show how to use org.hibernate.MappingException. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: lams   Source File: CollectionType.java    License: 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 2
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 3
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 4
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 5
Source Project: lams   Source File: SerializableToBlobType.java    License: 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 6
Source Project: lams   Source File: PersistentClass.java    License: 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 7
Source Project: uyuni   Source File: HibernateFactory.java    License: 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 8
@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 9
Source Project: lams   Source File: ForeignKey.java    License: 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 Project: lams   Source File: BasicCollectionLoader.java    License: 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 11
Source Project: lams   Source File: QueryPlanCache.java    License: 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 12
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 13
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 14
public ReactiveEntityLoader(
		OuterJoinLoadable persister,
		int batchSize,
		LockOptions lockOptions,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	this(
			persister,
			persister.getIdentifierType(),
			factory,
			loadQueryInfluencers,
			new EntityJoinWalker(
					persister,
					persister.getIdentifierColumnNames(),
					batchSize,
					lockOptions,
					factory,
					loadQueryInfluencers
			) );

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "Static select for entity %s [%s:%s]: %s",
				entityName,
				lockOptions.getLockMode(),
				lockOptions.getTimeOut(),
				getSQLString() );
	}
}
 
Example 15
Source Project: lams   Source File: PathExpressionParser.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void addJoin(String name, AssociationType joinableType) throws QueryException {
	try {
		joinSequence.addJoin( joinableType, name, joinType, currentColumns() );
	}
	catch ( MappingException me ) {
		throw new QueryException( me );
	}
}
 
Example 16
Source Project: Knowage-Server   Source File: Table.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public UniqueKey addUniqueKey(UniqueKey uniqueKey) {
	UniqueKey current = (UniqueKey) uniqueKeys.get( uniqueKey.getName() );
	if ( current != null ) {
		throw new MappingException( "UniqueKey " + uniqueKey.getName() + " already exists!" );
	}
	uniqueKeys.put( uniqueKey.getName(), uniqueKey );
	return uniqueKey;
}
 
Example 17
@Override
public ReactiveCollectionLoader createRealBatchingOneToManyInitializer(
		QueryableCollection persister,
		int maxBatchSize,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	final int[] batchSizes = ArrayHelper.getBatchSizes( maxBatchSize );
	final ReactiveCollectionLoader[] loaders = new ReactiveCollectionLoader[ batchSizes.length ];
	for ( int i = 0; i < batchSizes.length; i++ ) {
		loaders[i] = new ReactiveOneToManyLoader( persister, batchSizes[i], factory, loadQueryInfluencers );
	}
	return new ReactivePaddedBatchingCollectionInitializer( persister, batchSizes, loaders, factory, loadQueryInfluencers);
}
 
Example 18
protected final int determineJdbcTypeCode(Type type, Mapping mapping) throws QueryException {
	try {
		final int[] jdbcTypeCodes = type.sqlTypes( mapping );
		if ( jdbcTypeCodes.length != 1 ) {
			throw new QueryException( "multiple-column type in sum()" );
		}
		return jdbcTypeCodes[0];
	}
	catch ( MappingException me ) {
		throw new QueryException( me );
	}
}
 
Example 19
Source Project: lams   Source File: PersistentClass.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void checkPropertyColumnDuplication(Set distinctColumns, Iterator properties)
		throws MappingException {
	while ( properties.hasNext() ) {
		Property prop = (Property) properties.next();
		if ( prop.getValue() instanceof Component ) { //TODO: remove use of instanceof!
			Component component = (Component) prop.getValue();
			checkPropertyColumnDuplication( distinctColumns, component.getPropertyIterator() );
		}
		else {
			if ( prop.isUpdateable() || prop.isInsertable() ) {
				checkColumnDuplication( distinctColumns, prop.getColumnIterator() );
			}
		}
	}
}
 
Example 20
Source Project: lams   Source File: PropertyInferredData.java    License: GNU General Public License v2.0 5 votes vote down vote up
public AccessType getDefaultAccess() throws MappingException {
	AccessType accessType = defaultAccess;

	AccessType hibernateAccessType = AccessType.DEFAULT;
	AccessType jpaAccessType = AccessType.DEFAULT;

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

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

	if ( hibernateAccessType != AccessType.DEFAULT
			&& jpaAccessType != AccessType.DEFAULT
			&& hibernateAccessType != jpaAccessType ) {

		StringBuilder builder = new StringBuilder();
		builder.append( property.toString() );
		builder.append(
				" defines @AccessType and @Access with contradicting values. Use of @Access only is recommended."
		);
		throw new MappingException( builder.toString() );
	}

	if ( hibernateAccessType != AccessType.DEFAULT ) {
		accessType = hibernateAccessType;
	}
	else if ( jpaAccessType != AccessType.DEFAULT ) {
		accessType = jpaAccessType;
	}
	return accessType;
}
 
Example 21
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 22
Source Project: lams   Source File: PersistentClass.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Class getProxyInterface() {
	if ( proxyInterfaceName == null ) {
		return null;
	}
	try {
		if ( proxyInterface == null ) {
			proxyInterface = metadataBuildingContext.getBootstrapContext().getClassLoaderAccess().classForName( proxyInterfaceName );
		}
		return proxyInterface;
	}
	catch (ClassLoadingException e) {
		throw new MappingException( "proxy class not found: " + proxyInterfaceName, e );
	}
}
 
Example 23
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 24
Source Project: lams   Source File: Set.java    License: 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() );*/
}
 
Example 25
Source Project: lams   Source File: DerbyDialect.java    License: 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 26
Source Project: lams   Source File: EntityBinder.java    License: 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 27
Source Project: icure-backend   Source File: IndexCreator.java    License: 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 28
Source Project: lams   Source File: NativeQueryImpl.java    License: 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 29
@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 30
Source Project: lams   Source File: AbstractEntityTuplizer.java    License: 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 );
}