Java Code Examples for org.hibernate.engine.SessionFactoryImplementor#getEntityPersister()

The following examples show how to use org.hibernate.engine.SessionFactoryImplementor#getEntityPersister() . 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: AbstractEmptinessExpression.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
protected QueryableCollection getQueryableCollection(String entityName, String propertyName, SessionFactoryImplementor factory)
        throws HibernateException {
	PropertyMapping ownerMapping = ( PropertyMapping ) factory.getEntityPersister( entityName );
	Type type = ownerMapping.toType( propertyName );
	if ( !type.isCollectionType() ) {
		throw new MappingException(
		        "Property path [" + entityName + "." + propertyName + "] does not reference a collection"
		);
	}

	String role = ( ( CollectionType ) type ).getRole();
	try {
		return ( QueryableCollection ) factory.getCollectionPersister( role );
	}
	catch ( ClassCastException cce ) {
		throw new QueryException( "collection role is not queryable: " + role );
	}
	catch ( Exception e ) {
		throw new QueryException( "collection role not found: " + role );
	}
}
 
Example 2
Source File: AbstractEntityPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory, EntityMode entityMode) {
	if ( !hasSubclasses() ) {
		return this;
	}
	else {
		// TODO : really need a way to do something like :
		//      getTuplizer(entityMode).determineConcreteSubclassEntityName(instance)
		Class clazz = instance.getClass();
		if ( clazz == getMappedClass( entityMode ) ) {
			return this;
		}
		else {
			String subclassEntityName = getSubclassEntityName( clazz );
			if ( subclassEntityName == null ) {
				throw new HibernateException(
						"instance not of expected entity type: " + clazz.getName() +
						" is not a: " + getEntityName()
					);
			}
			else {
				return factory.getEntityPersister( subclassEntityName );
			}
		}
	}
}
 
Example 3
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int getHashCode(Object x, EntityMode entityMode, SessionFactoryImplementor factory) {
	EntityPersister persister = factory.getEntityPersister(associatedEntityName);
	if ( !persister.canExtractIdOutOfEntity() ) {
		return super.getHashCode(x, entityMode);
	}

	final Serializable id;
	if (x instanceof HibernateProxy) {
		id = ( (HibernateProxy) x ).getHibernateLazyInitializer().getIdentifier();
	}
	else {
		id = persister.getIdentifier(x, entityMode);
	}
	return persister.getIdentifierType().getHashCode(id, entityMode, factory);
}
 
Example 4
Source File: SubqueryExpression.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
	
	final SessionImplementor session = ( (CriteriaImpl) criteria ).getSession(); //ugly!
	final SessionFactoryImplementor factory = session.getFactory();
	
	final OuterJoinLoadable persister = (OuterJoinLoadable) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() );
	CriteriaQueryTranslator innerQuery = new CriteriaQueryTranslator( 
			factory, 
			criteriaImpl, 
			criteriaImpl.getEntityOrClassName(), //implicit polymorphism not supported (would need a union) 
			criteriaQuery.generateSQLAlias(),
			criteriaQuery
		);
	
	params = innerQuery.getQueryParameters(); //TODO: bad lifecycle....
	types = innerQuery.getProjectedTypes();
	
	//String filter = persister.filterFragment( innerQuery.getRootSQLALias(), session.getEnabledFilters() );
	
	String sql = new Select( factory.getDialect() )
		.setWhereClause( innerQuery.getWhereCondition() )
		.setGroupByClause( innerQuery.getGroupBy() )
		.setSelectClause( innerQuery.getSelect() )
		.setFromClause(
				persister.fromTableFragment( innerQuery.getRootSQLALias() ) +   
				persister.fromJoinFragment( innerQuery.getRootSQLALias(), true, false )
			)
		.toStatementString();
	
	final StringBuffer buf = new StringBuffer()
		.append( toLeftSqlString(criteria, criteriaQuery) );
	if (op!=null) buf.append(' ').append(op).append(' ');
	if (quantifier!=null) buf.append(quantifier).append(' ');
	return buf.append('(').append(sql).append(')')
		.toString();
}
 
Example 5
Source File: StructuredCacheEntry.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object destructure(Object item, SessionFactoryImplementor factory) {
	Map map = (Map) item;
	boolean lazyPropertiesUnfetched = ( (Boolean) map.get("_lazyPropertiesUnfetched") ).booleanValue();
	String subclass = (String) map.get("_subclass");
	Object version = map.get("_version");
	EntityPersister subclassPersister = factory.getEntityPersister(subclass);
	String[] names = subclassPersister.getPropertyNames();
	Serializable[] state = new Serializable[names.length];
	for ( int i=0; i<names.length; i++ ) {
		state[i] = (Serializable) map.get( names[i] );
	}
	return new CacheEntry(state, subclass, lazyPropertiesUnfetched, version);
}
 
Example 6
Source File: SessionFactoryHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Given a (potentially unqualified) class name, locate its persister.
 *
 * @param sfi The session factory implementor.
 * @param className The (potentially unqualified) class name.
 * @return The defined persister for this class, or null if none found.
 */
public static Queryable findQueryableUsingImports(SessionFactoryImplementor sfi, String className) {
	final String importedClassName = sfi.getImportedClassName( className );
	if ( importedClassName == null ) {
		return null;
	}
	try {
		return ( Queryable ) sfi.getEntityPersister( importedClassName );
	}
	catch ( MappingException me ) {
		return null;
	}
}
 
Example 7
Source File: BulkOperationCleanupAction.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** Create an action that will evict collection and entity regions based on queryspaces (table names).
 *  TODO: cache the autodetected information and pass it in instead.
 **/
public BulkOperationCleanupAction(SessionImplementor session, Set querySpaces) {
	this.session = session;

	Set tmpSpaces = new HashSet(querySpaces);
	SessionFactoryImplementor factory = session.getFactory();
	Iterator iterator = factory.getAllClassMetadata().entrySet().iterator();
	while ( iterator.hasNext() ) {
		Map.Entry entry = (Map.Entry) iterator.next();
		String entityName = (String) entry.getKey();
		EntityPersister persister = factory.getEntityPersister( entityName );
		Serializable[] entitySpaces = persister.getQuerySpaces();

		if (affectedEntity( querySpaces, entitySpaces )) {
			if ( persister.hasCache() ) {
				affectedEntityNames.add( persister.getEntityName() );
			}
			Set roles = session.getFactory().getCollectionRolesByEntityParticipant( persister.getEntityName() );
			if ( roles != null ) {
				affectedCollectionRoles.addAll( roles );
			}
			for ( int y = 0; y < entitySpaces.length; y++ ) {
				tmpSpaces.add( entitySpaces[y] );
			}
		}

	}
	this.spaces = (Serializable[]) tmpSpaces.toArray( new Serializable[tmpSpaces.size()] );		
}
 
Example 8
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isEqual(Object x, Object y, EntityMode entityMode, SessionFactoryImplementor factory) {
	EntityPersister persister = factory.getEntityPersister(associatedEntityName);
	if ( !persister.canExtractIdOutOfEntity() ) {
		return super.isEqual(x, y, entityMode);
	}

	Serializable xid;
	if (x instanceof HibernateProxy) {
		xid = ( (HibernateProxy) x ).getHibernateLazyInitializer()
				.getIdentifier();
	}
	else {
		xid = persister.getIdentifier(x, entityMode);
	}

	Serializable yid;
	if (y instanceof HibernateProxy) {
		yid = ( (HibernateProxy) y ).getHibernateLazyInitializer()
				.getIdentifier();
	}
	else {
		yid = persister.getIdentifier(y, entityMode);
	}

	return persister.getIdentifierType()
			.isEqual(xid, yid, entityMode, factory);
}
 
Example 9
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Load an instance by a unique key that is not the primary key.
 *
 * @param entityName The name of the entity to load
 * @param uniqueKeyPropertyName The name of the property defining the uniqie key.
 * @param key The unique key property value.
 * @param session The originating session.
 * @return The loaded entity
 * @throws HibernateException generally indicates problems performing the load.
 */
public Object loadByUniqueKey(
		String entityName, 
		String uniqueKeyPropertyName, 
		Object key, 
		SessionImplementor session) throws HibernateException {
	final SessionFactoryImplementor factory = session.getFactory();
	UniqueKeyLoadable persister = ( UniqueKeyLoadable ) factory.getEntityPersister( entityName );

	//TODO: implement caching?! proxies?!

	EntityUniqueKey euk = new EntityUniqueKey(
			entityName, 
			uniqueKeyPropertyName, 
			key, 
			getIdentifierOrUniqueKeyType( factory ),
			session.getEntityMode(), 
			session.getFactory()
	);

	final PersistenceContext persistenceContext = session.getPersistenceContext();
	Object result = persistenceContext.getEntity( euk );
	if ( result == null ) {
		result = persister.loadByUniqueKey( uniqueKeyPropertyName, key, session );
	}
	return result == null ? null : persistenceContext.proxyFor( result );
}
 
Example 10
Source File: DefaultLoadEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Object assembleCacheEntry(
		final CacheEntry entry,
		final Serializable id,
		final EntityPersister persister,
		final LoadEvent event) throws HibernateException {
	
	final Object optionalObject = event.getInstanceToLoad();
	final EventSource session = event.getSession();
	final SessionFactoryImplementor factory = session.getFactory();
	
	if ( log.isTraceEnabled() ) {
		log.trace(
				"assembling entity from second-level cache: " +
				MessageHelper.infoString( persister, id, factory )
			);
	}

	EntityPersister subclassPersister = factory.getEntityPersister( entry.getSubclass() );
	Object result = optionalObject == null ? 
			session.instantiate( subclassPersister, id ) : optionalObject;
			
	// make it circular-reference safe
	TwoPhaseLoad.addUninitializedCachedEntity( 
			new EntityKey( id, subclassPersister, session.getEntityMode() ), 
			result, 
			subclassPersister, 
			LockMode.NONE, 
			entry.areLazyPropertiesUnfetched(),
			entry.getVersion(),
			session
		);

	Type[] types = subclassPersister.getPropertyTypes();
	Object[] values = entry.assemble( result, id, subclassPersister, session.getInterceptor(), session ); // intializes result by side-effect
	TypeFactory.deepCopy( 
			values, 
			types, 
			subclassPersister.getPropertyUpdateability(), 
			values, 
			session
		);
	
	Object version = Versioning.getVersion( values, subclassPersister );
	if ( log.isTraceEnabled() ) log.trace( "Cached Version: " + version );
	
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	persistenceContext.addEntry( 
			result, 
			Status.MANAGED, 
			values, 
			null, 
			id, 
			version, 
			LockMode.NONE, 
			true, 
			subclassPersister, 
			false, 
			entry.areLazyPropertiesUnfetched() 
		);
	subclassPersister.afterInitialize( result, entry.areLazyPropertiesUnfetched(), session );
	persistenceContext.initializeNonLazyCollections();
	// upgrade the lock if necessary:
	//lock(result, lockMode);

	//PostLoad is needed for EJB3
	//TODO: reuse the PostLoadEvent...
	PostLoadEvent postLoadEvent = new PostLoadEvent(session).setEntity(result)
			.setId(id).setPersister(persister);
	PostLoadEventListener[] listeners = session.getListeners().getPostLoadEventListeners();
	for ( int i = 0; i < listeners.length; i++ ) {
		listeners[i].onPostLoad(postLoadEvent);
	}
	
	return result;
}
 
Example 11
Source File: EntityType.java    From cacheonix-core with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Retrieves the {@link Joinable} defining the associated entity.
 *
 * @param factory The session factory.
 * @return The associated joinable
 * @throws MappingException Generally indicates an invalid entity name.
 */
public Joinable getAssociatedJoinable(SessionFactoryImplementor factory) throws MappingException {
	return ( Joinable ) factory.getEntityPersister( associatedEntityName );
}