org.hibernate.EntityMode Java Examples

The following examples show how to use org.hibernate.EntityMode. 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: PersistentArrayHolder.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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
Source File: BatchFetchQueue.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
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
Source File: SessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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
Source File: HbmBinder.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #5
Source File: Subclass.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String getTuplizerImplClassName(EntityMode mode) {
	String impl = super.getTuplizerImplClassName( mode );
	if ( impl == null ) {
		impl = getSuperclass().getTuplizerImplClassName( mode );
	}
	return impl;
}
 
Example #6
Source File: EntityKey.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #7
Source File: ListType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #8
Source File: TimeType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #9
Source File: Dom4jAccessorTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #10
Source File: PersistentMap.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #11
Source File: EntityUniqueKey.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #12
Source File: FilterKey.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #13
Source File: CollectionType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 #14
Source File: Example.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #15
Source File: AbstractEntityTuplizer.java    From lams with 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 #16
Source File: AbstractDelegatingSessionFactoryBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public T applyEntityTuplizer(
		EntityMode entityMode,
		Class<? extends EntityTuplizer> tuplizerClass) {
	delegate.applyEntityTuplizer( entityMode, tuplizerClass );
	return getThis();
}
 
Example #17
Source File: ComponentMetamodel.java    From lams with 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 #18
Source File: DefaultFlushEntityEventListener.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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
Source File: WrapVisitor.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #20
Source File: PersistentBag.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #21
Source File: MapType.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #22
Source File: HibernateEntityMapper.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #23
Source File: ForeignKeys.java    From lams with 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 #24
Source File: Dom4jAccessorTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 #25
Source File: AbstractType.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public int compare(Object x, Object y, EntityMode entityMode) {
	return ( (Comparable) x ).compareTo(y);
}
 
Example #26
Source File: ComponentType.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public EntityMode getEntityMode() {
	return entityMode;
}
 
Example #27
Source File: ClobType.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public int compare(Object x, Object y, EntityMode entityMode) {
	return 0; //lobs cannot be compared
}
 
Example #28
Source File: CustomPersister.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public EntityPersister getSubclassEntityPersister(Object instance, SessionFactoryImplementor factory, EntityMode entityMode) {
	checkEntityMode( entityMode );
	return this;
}
 
Example #29
Source File: DynamicMapOneToOneTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void configure(Configuration cfg) {
	cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "false");
	cfg.setProperty(Environment.GENERATE_STATISTICS, "true");
	cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.MAP.toString() );
}
 
Example #30
Source File: StatelessSessionImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public EntityMode getEntityMode() {
	return EntityMode.POJO;
}