下面列出了怎么用org.hibernate.EntityMode的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
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;
}
/**
* 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 + "]" );
}
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;
}
/**
* 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
}
public String getTuplizerImplClassName(EntityMode mode) {
String impl = super.getTuplizerImplClassName( mode );
if ( impl == null ) {
impl = getSuperclass().getTuplizerImplClassName( mode );
}
return impl;
}
/**
* 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();
}
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;
}
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 );
}
@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 );
}
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
);
}
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 );
}
}
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();
}
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 );
}
}
@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);
}
}
/**
* 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;
}
}
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" ) );
}
}
/**
* 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);
}
}
}
@Override
public T applyEntityTuplizer(
EntityMode entityMode,
Class<? extends EntityTuplizer> tuplizerClass) {
delegate.applyEntityTuplizer( entityMode, tuplizerClass );
return getThis();
}
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 ) );
}
}
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 );
}
}
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;
}
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 );
}
/**
* 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()
);
}
public void configure(Configuration cfg) {
cfg.setProperty( Environment.DEFAULT_ENTITY_MODE, EntityMode.DOM4J.toString() );
}
public EntityMode getDefaultEntityMode() {
return sessionFactoryOptions.getDefaultEntityMode();
}
public void addTuplizer(EntityMode entityMode, String implClassName) {
if ( tuplizerImpls == null ) {
tuplizerImpls = new HashMap<>();
}
tuplizerImpls.put( entityMode, implClassName );
}
public int getHashCode(Object x, EntityMode entityMode) {
return System.identityHashCode(x);
}
public Object instantiate(Serializable id, EntityMode entityMode) throws HibernateException {
checkEntityMode( entityMode );
Custom c = new Custom();
c.id = (String) id;
return c;
}
protected boolean initializeImmediately(EntityMode entityMode) {
return entityMode == EntityMode.DOM4J;
}