Java Code Examples for org.hibernate.EntityMode

The following examples show how to use org.hibernate.EntityMode. 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
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
	EntityMode entityMode = getSession().getEntityMode();
	int length = /*(array==null) ? tempList.size() :*/ Array.getLength(array);
	Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length );
	for ( int i=0; i<length; i++ ) {
		Object elt = /*(array==null) ? tempList.get(i) :*/ Array.get(array, i);
		try {
			Array.set( result, i, persister.getElementType().deepCopy(elt, entityMode, persister.getFactory()) );
		}
		catch (IllegalArgumentException iae) {
			log.error("Array element type error", iae);
			throw new HibernateException( "Array element type error", iae );
		}
	}
	return result;
}
 
Example 2
private boolean isCached(
		Serializable collectionKey,
		CollectionPersister persister,
		EntityMode entityMode) {
	if ( persister.hasCache() ) {
		CacheKey cacheKey = new CacheKey(
				collectionKey,
		        persister.getKeyType(),
		        persister.getRole(),
		        entityMode,
		        context.getSession().getFactory()
		);
		return persister.getCache().getCache().get( cacheKey ) != null;
	}
	return false;
}
 
Example 3
/**
 * Constructor used in building "child sessions".
 *
 * @param parent The parent session
 * @param entityMode
 */
private SessionImpl(SessionImpl parent, EntityMode entityMode) {
	super( parent.factory );
	this.rootSession = parent;
	this.timestamp = parent.timestamp;
	this.jdbcContext = parent.jdbcContext;
	this.interceptor = parent.interceptor;
	this.listeners = parent.listeners;
	this.actionQueue = new ActionQueue( this );
	this.entityMode = entityMode;
	this.persistenceContext = new StatefulPersistenceContext( this );
	this.flushBeforeCompletionEnabled = false;
	this.autoCloseSessionEnabled = false;
	this.connectionReleaseMode = null;

	if ( factory.getStatistics().isStatisticsEnabled() ) {
		factory.getStatisticsImplementor().openSession();
	}

	log.debug( "opened session [" + entityMode + "]" );
}
 
Example 4
public Serializable getSnapshot(CollectionPersister persister) throws HibernateException {
	EntityMode entityMode = getSession().getEntityMode();
	HashMap clonedMap = new HashMap( map.size() );
	Iterator iter = map.entrySet().iterator();
	while ( iter.hasNext() ) {
		Map.Entry e = (Map.Entry) iter.next();
		final Object copy = persister.getElementType()
			.deepCopy( e.getValue(), entityMode, persister.getFactory() );
		clonedMap.put( e.getKey(), copy );
	}
	return clonedMap;
}
 
Example 5
/**
 * Construct a unique identifier for an entity class instance
 */
public EntityKey(Serializable id, EntityPersister persister, EntityMode entityMode) {
	if ( id == null ) {
		throw new AssertionFailure( "null identifier" );
	}
	this.identifier = id; 
	this.entityMode = entityMode;
	this.rootEntityName = persister.getRootEntityName();
	this.entityName = persister.getEntityName();
	this.identifierType = persister.getIdentifierType();
	this.isBatchLoadable = persister.isBatchLoadable();
	this.factory = persister.getFactory();
	hashCode = generateHashCode(); //cache the hashcode
}
 
Example 6
public String getTuplizerImplClassName(EntityMode mode) {
	String impl = super.getTuplizerImplClassName( mode );
	if ( impl == null ) {
		impl = getSuperclass().getTuplizerImplClassName( mode );
	}
	return impl;
}
 
Example 7
/**
 * instantiate a collection wrapper (called when loading an object)
 *
 * @param key The collection owner key
 * @param session The session from which the request is originating.
 * @param owner The collection owner
 * @return The collection
 */
public Object getCollection(Serializable key, SessionImplementor session, Object owner) {

	CollectionPersister persister = getPersister( session );
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	final EntityMode entityMode = session.getEntityMode();

	if (entityMode==EntityMode.DOM4J && !isEmbeddedInXML) {
		return UNFETCHED_COLLECTION;
	}

	// check if collection is currently being loaded
	PersistentCollection collection = persistenceContext.getLoadContexts().locateLoadingCollection( persister, key );
	if ( collection == null ) {
		// check if it is already completely loaded, but unowned
		collection = persistenceContext.useUnownedCollection( new CollectionKey(persister, key, entityMode) );
		if ( collection == null ) {
			// create a new collection wrapper, to be initialized later
			collection = instantiate( session, persister, key );
			collection.setOwner( owner );

			persistenceContext.addUninitializedCollection( persister, collection, key );

			// some collections are not lazy:
			if ( initializeImmediately( entityMode ) ) {
				session.initializeCollection( collection, false );
			}
			else if ( !persister.isLazy() ) {
				persistenceContext.addNonLazyCollection( collection );
			}

			if ( hasHolder( entityMode ) ) {
				session.getPersistenceContext().addCollectionHolder( collection );
			}
		}
	}
	collection.setOwner( owner );
	return collection.getValue();
}
 
Example 8
private EntityMode getEntityMode(Criteria criteria, CriteriaQuery criteriaQuery) {
	EntityPersister meta = criteriaQuery.getFactory()
			.getEntityPersister( criteriaQuery.getEntityName(criteria) );
	EntityMode result = meta.guessEntityMode(entity);
	if (result==null) {
		throw new ClassCastException( entity.getClass().getName() );
	}
	return result;
}
 
Example 9
public void testStringTextExtraction() throws Throwable {
	Property property = generateTextProperty();
	Getter getter = PropertyAccessorFactory.getPropertyAccessor( property, EntityMode.DOM4J )
			.getGetter( null, null );
	String name = ( String ) getter.get( DOM );
	assertEquals( "Not equals", "description...", name );
}
 
Example 10
Source Project: lams   Source File: AbstractEntityTuplizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setIdentifier(Object entity, Serializable id, EntityMode entityMode, SharedSessionContractImplementor session) {
	final Object[] extractedValues = mappedIdentifierType.getPropertyValues( id, entityMode );
	final Object[] injectionValues = new Object[extractedValues.length];
	final PersistenceContext persistenceContext = session.getPersistenceContext();
	for ( int i = 0; i < virtualIdComponent.getSubtypes().length; i++ ) {
		final Type virtualPropertyType = virtualIdComponent.getSubtypes()[i];
		final Type idClassPropertyType = mappedIdentifierType.getSubtypes()[i];
		if ( virtualPropertyType.isEntityType() && !idClassPropertyType.isEntityType() ) {
			if ( session == null ) {
				throw new AssertionError(
						"Deprecated version of getIdentifier (no session) was used but session was required"
				);
			}
			final String associatedEntityName = ( (EntityType) virtualPropertyType ).getAssociatedEntityName();
			final EntityKey entityKey = session.generateEntityKey(
					(Serializable) extractedValues[i],
					sessionFactory.getMetamodel().entityPersister( associatedEntityName )
			);
			// it is conceivable there is a proxy, so check that first
			Object association = persistenceContext.getProxy( entityKey );
			if ( association == null ) {
				// otherwise look for an initialized version
				association = persistenceContext.getEntity( entityKey );
				if ( association == null ) {
					// get the association out of the entity itself
					association = sessionFactory.getMetamodel().entityPersister( entityName ).getPropertyValue(
							entity,
							virtualIdComponent.getPropertyNames()[i]
					);
				}
			}
			injectionValues[i] = association;
		}
		else {
			injectionValues[i] = extractedValues[i];
		}
	}
	virtualIdComponent.setPropertyValues( entity, injectionValues, entityMode );
}
 
Example 11
Source Project: lams   Source File: ComponentMetamodel.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ComponentMetamodel(Component component, ComponentTuplizerFactory componentTuplizerFactory){
	this.role = component.getRoleName();
	this.isKey = component.isKey();
	propertySpan = component.getPropertySpan();
	properties = new StandardProperty[propertySpan];
	Iterator itr = component.getPropertyIterator();
	int i = 0;
	while ( itr.hasNext() ) {
		Property property = ( Property ) itr.next();
		properties[i] = PropertyFactory.buildStandardProperty( property, false );
		propertyIndexes.put( property.getName(), i );
		i++;
	}

	entityMode = component.hasPojoRepresentation() ? EntityMode.POJO : EntityMode.MAP;

	// todo : move this to SF per HHH-3517; also see HHH-1907 and ComponentMetamodel
	final String tuplizerClassName = component.getTuplizerImplClassName( entityMode );
	this.componentTuplizer = tuplizerClassName == null ? componentTuplizerFactory.constructDefaultTuplizer(
			entityMode,
			component
	) : componentTuplizerFactory.constructTuplizer( tuplizerClassName, component );

	final ConfigurationService cs = component.getMetadata().getMetadataBuildingOptions().getServiceRegistry()
			.getService(ConfigurationService.class);

	this.createEmptyCompositesEnabled = ConfigurationHelper.getBoolean(
			Environment.CREATE_EMPTY_COMPOSITES_ENABLED,
			cs.getSettings(),
			false
	);
}
 
Example 12
void process(Object object, EntityPersister persister) throws HibernateException {
	EntityMode entityMode = getSession().getEntityMode();
	Object[] values = persister.getPropertyValues( object, entityMode );
	Type[] types = persister.getPropertyTypes();
	processEntityPropertyValues(values, types);
	if ( isSubstitutionRequired() ) {
		persister.setPropertyValues( object, values, entityMode );
	}
}
 
Example 13
public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException {
	//if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags");
	Type elementType = persister.getElementType();
	EntityMode entityMode = getSession().getEntityMode();
	ArrayList deletes = new ArrayList();
	List sn = (List) getSnapshot();
	Iterator olditer = sn.iterator();
	int i=0;
	while ( olditer.hasNext() ) {
		Object old = olditer.next();
		Iterator newiter = bag.iterator();
		boolean found = false;
		if ( bag.size()>i && elementType.isSame( old, bag.get(i++), entityMode ) ) {
		//a shortcut if its location didn't change!
			found = true;
		}
		else {
			//search for it
			//note that this code is incorrect for other than one-to-many
			while ( newiter.hasNext() ) {
				if ( elementType.isSame( old, newiter.next(), entityMode ) ) {
					found = true;
					break;
				}
			}
		}
		if (!found) deletes.add(old);
	}
	return deletes.iterator();
}
 
Example 14
public PersistentCollection wrap(SessionImplementor session, Object collection) {
	if ( session.getEntityMode()==EntityMode.DOM4J ) {
		return new PersistentMapElementHolder( session, (Element) collection );
	}
	else {
		return new PersistentMap( session, (java.util.Map) collection );
	}
}
 
Example 15
@Override
public void setChild(String name, Entity entity) throws LayerException {
	if (entity != null) {
		metadata.setPropertyValue(object, name, ((HibernateEntity) entity).getObject(), EntityMode.POJO);
	} else {
		metadata.setPropertyValue(object, name, null, EntityMode.POJO);
	}
}
 
Example 16
Source Project: lams   Source File: ForeignKeys.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return null if the argument is an "unsaved" entity (ie. one with no existing database row), or the
 * input argument otherwise.  This is how Hibernate avoids foreign key constraint violations.
 *
 * @param value An entity attribute value
 * @param type An entity attribute type
 *
 * @return {@code null} if the argument is an unsaved entity; otherwise return the argument.
 */
private Object nullifyTransientReferences(final Object value, final Type type) {
	if ( value == null ) {
		return null;
	}
	else if ( type.isEntityType() ) {
		final EntityType entityType = (EntityType) type;
		if ( entityType.isOneToOne() ) {
			return value;
		}
		else {
			final String entityName = entityType.getAssociatedEntityName();
			return isNullifiable( entityName, value ) ? null : value;
		}
	}
	else if ( type.isAnyType() ) {
		return isNullifiable( null, value ) ? null : value;
	}
	else if ( type.isComponentType() ) {
		final CompositeType actype = (CompositeType) type;
		final Object[] subvalues = actype.getPropertyValues( value, session );
		final Type[] subtypes = actype.getSubtypes();
		boolean substitute = false;
		for ( int i = 0; i < subvalues.length; i++ ) {
			final Object replacement = nullifyTransientReferences( subvalues[i], subtypes[i] );
			if ( replacement != subvalues[i] ) {
				substitute = true;
				subvalues[i] = replacement;
			}
		}
		if ( substitute ) {
			// todo : need to account for entity mode on the CompositeType interface :(
			actype.setPropertyValues( value, subvalues, EntityMode.POJO );
		}
		return value;
	}
	else {
		return value;
	}
}
 
Example 17
private static void bindDom4jRepresentation(Element node, PersistentClass entity,
		Mappings mappings, java.util.Map inheritedMetas) {
	String nodeName = node.attributeValue( "node" );
	if (nodeName==null) nodeName = StringHelper.unqualify( entity.getEntityName() );
	entity.setNodeName(nodeName);

	Element tuplizer = locateTuplizerDefinition( node, EntityMode.DOM4J );
	if ( tuplizer != null ) {
		entity.addTuplizer( EntityMode.DOM4J, tuplizer.attributeValue( "class" ) );
	}
}
 
Example 18
/**
 * Flushes a single entity's state to the database, by scheduling
 * an update action, if necessary
 */
public void onFlushEntity(FlushEntityEvent event) throws HibernateException {
	final Object entity = event.getEntity();
	final EntityEntry entry = event.getEntityEntry();
	final EventSource session = event.getSession();
	final EntityPersister persister = entry.getPersister();
	final Status status = entry.getStatus();
	final EntityMode entityMode = session.getEntityMode();
	final Type[] types = persister.getPropertyTypes();

	final boolean mightBeDirty = entry.requiresDirtyCheck(entity);

	final Object[] values = getValues( entity, entry, entityMode, mightBeDirty, session );

	event.setPropertyValues(values);

	//TODO: avoid this for non-new instances where mightBeDirty==false
	boolean substitute = wrapCollections( session, persister, types, values);

	if ( isUpdateNecessary( event, mightBeDirty ) ) {
		substitute = scheduleUpdate( event ) || substitute;
	}

	if ( status != Status.DELETED ) {
		// now update the object .. has to be outside the main if block above (because of collections)
		if (substitute) persister.setPropertyValues( entity, values, entityMode );

		// Search for collections by reachability, updating their role.
		// We don't want to touch collections reachable from a deleted object
		if ( persister.hasCollections() ) {
			new FlushVisitor(session, entity).processEntityPropertyValues(values, types);
		}
	}

}
 
Example 19
@Override
public T applyEntityTuplizer(
		EntityMode entityMode,
		Class<? extends EntityTuplizer> tuplizerClass) {
	delegate.applyEntityTuplizer( entityMode, tuplizerClass );
	return getThis();
}
 
Example 20
public FilterKey(String name, Map params, Map types, EntityMode entityMode) {
	filterName = name;
	Iterator iter = params.entrySet().iterator();
	while ( iter.hasNext() ) {
		Map.Entry me = (Map.Entry) iter.next();
		Type type = (Type) types.get( me.getKey() );
		filterParameters.put( me.getKey(), new TypedValue( type, me.getValue(), entityMode ) );
	}
}
 
Example 21
public PersistentCollection wrap(SessionImplementor session, Object collection) {
	if ( session.getEntityMode()==EntityMode.DOM4J ) {
		return new PersistentListElementHolder( session, (Element) collection );
	}
	else {
		return new PersistentList( session, (List) collection );
	}
}
 
Example 22
public int getHashCode(Object x, EntityMode entityMode) {
	Calendar calendar = java.util.Calendar.getInstance();
	calendar.setTime( (java.util.Date) x );
	int hashCode = 1;
	hashCode = 31 * hashCode + calendar.get(Calendar.HOUR_OF_DAY);
	hashCode = 31 * hashCode + calendar.get(Calendar.MINUTE);
	hashCode = 31 * hashCode + calendar.get(Calendar.SECOND);
	hashCode = 31 * hashCode + calendar.get(Calendar.MILLISECOND);
	return hashCode;
}
 
Example 23
public void testLongAttributeExtraction() throws Throwable {
	Property property = generateIdProperty();
	Getter getter = PropertyAccessorFactory.getPropertyAccessor( property, EntityMode.DOM4J )
			.getGetter( null, null );
	Long id = ( Long ) getter.get( DOM );
	assertEquals( "Not equals", new Long( 123 ), id );
}
 
Example 24
/**
 * Custom deserialization routine used during deserialization of a
 * Session/PersistenceContext for increased performance.
 *
 * @param ois The stream from which to read the entry.
 * @param session The session being deserialized.
 * @return The deserialized EntityEntry
 * @throws IOException
 * @throws ClassNotFoundException
 */
static EntityUniqueKey deserialize(
		ObjectInputStream ois,
        SessionImplementor session) throws IOException, ClassNotFoundException {
	return new EntityUniqueKey(
			( String ) ois.readObject(),
	        ( String ) ois.readObject(),
	        ois.readObject(),
	        ( Type ) ois.readObject(),
	        ( EntityMode ) ois.readObject(),
	        session.getFactory()
	);
}
 
Example 25
public void configure(Configuration cfg) {
	cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.DOM4J.toString() );
}
 
Example 26
Source Project: lams   Source File: Settings.java    License: GNU General Public License v2.0 4 votes vote down vote up
public EntityMode getDefaultEntityMode() {
	return sessionFactoryOptions.getDefaultEntityMode();
}
 
Example 27
Source Project: lams   Source File: Component.java    License: GNU General Public License v2.0 4 votes vote down vote up
public void addTuplizer(EntityMode entityMode, String implClassName) {
	if ( tuplizerImpls == null ) {
		tuplizerImpls = new HashMap<>();
	}
	tuplizerImpls.put( entityMode, implClassName );
}
 
Example 28
public int getHashCode(Object x, EntityMode entityMode) {
	return System.identityHashCode(x);
}
 
Example 29
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException {
	checkEntityMode( entityMode );
	Custom c = new Custom();
	c.id = (String) id;
	return c;
}
 
Example 30
protected boolean initializeImmediately(EntityMode entityMode) {
	return entityMode == EntityMode.DOM4J;
}
 
Example 31
public void setPropertyValues(Object component, Object[] values, EntityMode entityMode)
		throws HibernateException {
	tuplizerMapping.getTuplizer( entityMode ).setPropertyValues( component, values );
}
 
Example 32
public TypedValue(Type type, Object value, EntityMode entityMode) {
	this.type = type;
	this.value=value;
	this.entityMode = entityMode;
}
 
Example 33
Source Project: lams   Source File: AbstractEntityPersister.java    License: GNU General Public License v2.0 4 votes vote down vote up
@Override
public EntityMode getEntityMode() {
	return entityMetamodel.getEntityMode();
}
 
Example 34
/**
 * Return the names of all persistent (mapped) classes that extend or implement the
 * given class or interface, accounting for implicit/explicit polymorphism settings
 * and excluding mapped subclasses/joined-subclasses of other classes in the result.
 */
public String[] getImplementors(String className) throws MappingException {

	final Class clazz;
	try {
		clazz = ReflectHelper.classForName(className);
	}
	catch (ClassNotFoundException cnfe) {
		return new String[] { className }; //for a dynamic-class
	}

	ArrayList results = new ArrayList();
	Iterator iter = entityPersisters.values().iterator();
	while ( iter.hasNext() ) {
		//test this entity to see if we must query it
		EntityPersister testPersister = (EntityPersister) iter.next();
		if ( testPersister instanceof Queryable ) {
			Queryable testQueryable = (Queryable) testPersister;
			String testClassName = testQueryable.getEntityName();
			boolean isMappedClass = className.equals(testClassName);
			if ( testQueryable.isExplicitPolymorphism() ) {
				if ( isMappedClass ) {
					return new String[] {className}; //NOTE EARLY EXIT
				}
			}
			else {
				if (isMappedClass) {
					results.add(testClassName);
				}
				else {
					final Class mappedClass = testQueryable.getMappedClass( EntityMode.POJO );
					if ( mappedClass!=null && clazz.isAssignableFrom( mappedClass ) ) {
						final boolean assignableSuperclass;
						if ( testQueryable.isInherited() ) {
							Class mappedSuperclass = getEntityPersister( testQueryable.getMappedSuperclass() ).getMappedClass( EntityMode.POJO);
							assignableSuperclass = clazz.isAssignableFrom(mappedSuperclass);
						}
						else {
							assignableSuperclass = false;
						}
						if ( !assignableSuperclass ) {
							results.add( testClassName );
						}
					}
				}
			}
		}
	}
	return (String[]) results.toArray( new String[ results.size() ] );
}
 
Example 35
@Override
public Entity getChild(String name) throws LayerException {
	Object child = (object == null ? null : metadata.getPropertyValue(object, name, EntityMode.POJO));
	return child == null ? null : new HibernateEntity(child);
}
 
Example 36
public boolean isEqual(Object x, Object y, EntityMode entityMode) {
	return EqualsHelper.equals(x, y);
}
 
Example 37
public EntityTuplizer getTuplizer(EntityMode entityMode) {
	return (EntityTuplizer) tuplizerMapping.getTuplizer( entityMode );
}
 
Example 38
public boolean isEqual(Object x, Object y, EntityMode entityMode, SessionFactoryImplementor factory) {
	return isEqual(x, y, entityMode);
}
 
Example 39
public Serializable getIdentifier(Object object, EntityMode entityMode) throws HibernateException {
	checkEntityMode( entityMode );
	return ( (Custom) object ).id;
}
 
Example 40
/**
 * This method does not populate the component parent
 */
public Object instantiate(EntityMode entityMode) throws HibernateException {
	return tuplizerMapping.getTuplizer( entityMode ).instantiate();
}