下面列出了怎么用org.hibernate.type.EntityType的API类实例代码及写法,或者点击链接到github查看源代码。
public void remove() {
if (!single) {
throw new UnsupportedOperationException("Not a single column hibernate query result set");
}
if (currentResult==null) {
throw new IllegalStateException("Called Iterator.remove() before next()");
}
if ( !( types[0] instanceof EntityType ) ) {
throw new UnsupportedOperationException("Not an entity");
}
session.delete(
( (EntityType) types[0] ).getAssociatedEntityName(),
currentResult,
false,
null
);
}
private void findKeyManyToOneTargetIndices(
ArrayList<Integer> keyManyToOneTargetIndices,
OuterJoinableAssociation joinWithCompositeId,
CompositeType componentType) {
for ( Type subType : componentType.getSubtypes() ) {
if ( subType.isEntityType() ) {
Integer index = locateKeyManyToOneTargetIndex( joinWithCompositeId, (EntityType) subType );
if ( index != null ) {
keyManyToOneTargetIndices.add( index );
}
}
else if ( subType.isComponentType() ) {
findKeyManyToOneTargetIndices(
keyManyToOneTargetIndices,
joinWithCompositeId,
(CompositeType) subType
);
}
}
}
private Integer locateKeyManyToOneTargetIndex(OuterJoinableAssociation joinWithCompositeId, EntityType keyManyToOneType) {
// the lhs (if one) is a likely candidate
if ( joinWithCompositeId.getLhsAlias() != null ) {
final OuterJoinableAssociation lhs = associationsByAlias.get( joinWithCompositeId.getLhsAlias() );
if ( keyManyToOneType.getAssociatedEntityName( factory ).equals( lhs.getJoinableType().getAssociatedEntityName( factory ) ) ) {
return positionsByAlias.get( lhs.getRhsAlias() );
}
}
// otherwise, seek out OuterJoinableAssociation which are RHS of given OuterJoinableAssociation
// (joinWithCompositeId)
for ( OuterJoinableAssociation oja : associationsByAlias.values() ) {
if ( oja.getLhsAlias() != null && oja.getLhsAlias().equals( joinWithCompositeId.getRhsAlias() ) ) {
if ( keyManyToOneType.equals( oja.getJoinableType() ) ) {
return positionsByAlias.get( oja.getLhsAlias() );
}
}
}
return null;
}
/**
* Does the mapping, and Hibernate default semantics, specify that
* this association should be fetched by outer joining
*/
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type)
throws MappingException {
if ( !type.isEntityType() && !type.isCollectionType() ) {
return false;
}
else {
if ( config == FetchMode.JOIN ) {
return true;
}
if ( config == FetchMode.SELECT ) {
return false;
}
if ( type.isEntityType() ) {
//TODO: look at the owning property and check that it
// isn't lazy (by instrumentation)
EntityType entityType = (EntityType) type;
EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
return !persister.hasProxy();
}
else {
return false;
}
}
}
private void registerNonExists(EntityFetch fetch) {
final EntityType fetchedType = fetch.getFetchedType();
if ( ! fetchedType.isOneToOne() ) {
return;
}
final EntityReferenceProcessingState fetchOwnerState = getOwnerProcessingState( fetch );
if ( fetchOwnerState == null ) {
throw new IllegalStateException( "Could not locate fetch owner state" );
}
final EntityKey ownerEntityKey = fetchOwnerState.getEntityKey();
if ( ownerEntityKey == null ) {
throw new IllegalStateException( "Could not locate fetch owner EntityKey" );
}
session.getPersistenceContext().addNullProperty(
ownerEntityKey,
fetchedType.getPropertyName()
);
}
private EntityReferenceAliases createCollectionElementAliases(
CollectionPersister collectionPersister,
String tableAlias,
String elementQuerySpaceUid) {
if ( !collectionPersister.getElementType().isEntityType() ) {
return null;
}
else {
final EntityType entityElementType = (EntityType) collectionPersister.getElementType();
return generateEntityReferenceAliases(
elementQuerySpaceUid,
tableAlias,
(EntityPersister) entityElementType.getAssociatedJoinable( sessionFactory() )
);
}
}
public JoinDefinedByMetadata createEntityJoin(
QuerySpace leftHandSide,
String lhsPropertyName,
EntityQuerySpace rightHandSide,
boolean rightHandSideRequired,
EntityType joinedPropertyType,
SessionFactoryImplementor sessionFactory) {
return new JoinImpl(
leftHandSide,
lhsPropertyName,
rightHandSide,
determineRhsColumnNames( joinedPropertyType, sessionFactory ),
joinedPropertyType,
rightHandSideRequired
);
}
private String getElementName(PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
String name;
if ( element.isOneToMany ) {
name = element.alias;
}
else {
Type type = element.elementType;
if ( type.isEntityType() ) { //ie. a many-to-many
String entityName = ( ( EntityType ) type ).getAssociatedEntityName();
name = pathExpressionParser.continueFromManyToMany( entityName, element.elementColumns, q );
}
else {
throw new QueryException( "illegally dereferenced collection element" );
}
}
return name;
}
private void doInitialize(FromClause fromClause, String tableAlias, String className, String classAlias,
EntityPersister persister, EntityType type) {
if ( initialized ) {
throw new IllegalStateException( "Already initialized!!" );
}
this.fromClause = fromClause;
this.tableAlias = tableAlias;
this.className = className;
this.classAlias = classAlias;
this.elementType = new FromElementType( this, persister, type );
// Register the FromElement with the FROM clause, now that we have the names and aliases.
fromClause.registerFromElement( this );
if ( log.isDebugEnabled() ) {
log.debug( fromClause + " : " + className + " ("
+ ( classAlias == null ? "no alias" : classAlias ) + ") -> " + tableAlias );
}
}
@Override
public BidirectionalEntityReference buildBidirectionalEntityReference(
AssociationAttributeDefinition attributeDefinition,
FetchStrategy fetchStrategy,
EntityReference targetEntityReference) {
final EntityType fetchedType = (EntityType) attributeDefinition.getType();
final EntityPersister fetchedPersister = attributeDefinition.toEntityDefinition().getEntityPersister();
if ( fetchedPersister == null ) {
throw new WalkingException(
String.format(
"Unable to locate EntityPersister [%s] for bidirectional entity reference [%s]",
fetchedType.getAssociatedEntityName(),
attributeDefinition.getName()
)
);
}
final BidirectionalEntityReference bidirectionalEntityReference =
new BidirectionalEntityReferenceImpl( this, attributeDefinition, targetEntityReference );
addBidirectionalEntityReference( bidirectionalEntityReference );
return bidirectionalEntityReference;
}
protected void initIdentifierPropertyPaths(
final String path,
final EntityType etype,
final String[] columns,
final String[] columnReaders,
final String[] columnReaderTemplates,
final Mapping factory) throws MappingException {
Type idtype = etype.getIdentifierOrUniqueKeyType( factory );
String idPropName = etype.getIdentifierOrUniqueKeyPropertyName( factory );
boolean hasNonIdentifierPropertyNamedId = hasNonIdentifierPropertyNamedId( etype, factory );
if ( etype.isReferenceToPrimaryKey() ) {
if ( !hasNonIdentifierPropertyNamedId ) {
String idpath1 = extendPath( path, EntityPersister.ENTITY_ID );
addPropertyPath( idpath1, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
initPropertyPaths( idpath1, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
}
}
if ( idPropName != null ) {
String idpath2 = extendPath( path, idPropName );
addPropertyPath( idpath2, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
initPropertyPaths( idpath2, idtype, columns, columnReaders, columnReaderTemplates, null, factory );
}
}
/**
* Cascade an action to a to-one association or any type
*/
private static void cascadeToOne(
final CascadingAction action,
final EventSource eventSource,
final Object parent,
final Object child,
final Type type,
final CascadeStyle style,
final Object anything,
final boolean isCascadeDeleteEnabled) {
final String entityName = type.isEntityType()
? ( (EntityType) type ).getAssociatedEntityName()
: null;
if ( style.reallyDoCascade( action ) ) {
//not really necessary, but good for consistency...
eventSource.getPersistenceContext().addChildParent( child, parent );
try {
action.cascade( eventSource, child, entityName, anything, isCascadeDeleteEnabled );
}
finally {
eventSource.getPersistenceContext().removeChildParent( child );
}
}
}
public void remove() {
if ( !single ) {
throw new UnsupportedOperationException( "Not a single column hibernate query result set" );
}
if ( currentResult == null ) {
throw new IllegalStateException( "Called Iterator.remove() before next()" );
}
if ( !( types[0] instanceof EntityType ) ) {
throw new UnsupportedOperationException( "Not an entity" );
}
session.delete(
( (EntityType) types[0] ).getAssociatedEntityName(),
currentResult,
false,
null
);
}
/**
* Is the given property name a reference to the primary key of the associated
* entity construed by the given entity type?
* <p/>
* For example, consider a fragment like order.customer.id
* (where order is a from-element alias). Here, we'd have:
* propertyName = "id" AND
* owningType = ManyToOneType(Customer)
* and are being asked to determine whether "customer.id" is a reference
* to customer's PK...
*
* @param propertyName The name of the property to check.
* @param owningType The type represeting the entity "owning" the property
*
* @return True if propertyName references the entity's (owningType->associatedEntity)
* primary key; false otherwise.
*/
private boolean isReferenceToPrimaryKey(String propertyName, EntityType owningType) {
EntityPersister persister = getSessionFactoryHelper()
.getFactory()
.getEntityPersister( owningType.getAssociatedEntityName() );
if ( persister.getEntityMetamodel().hasNonIdentifierPropertyNamedId() ) {
// only the identifier property field name can be a reference to the associated entity's PK...
return propertyName.equals( persister.getIdentifierPropertyName() ) && owningType.isReferenceToPrimaryKey();
}
// here, we have two possibilities:
// 1) the property-name matches the explicitly identifier property name
// 2) the property-name matches the implicit 'id' property name
// the referenced node text is the special 'id'
if ( EntityPersister.ENTITY_ID.equals( propertyName ) ) {
return owningType.isReferenceToPrimaryKey();
}
String keyPropertyName = getSessionFactoryHelper().getIdentifierOrUniqueKeyPropertyName( owningType );
return keyPropertyName != null && keyPropertyName.equals( propertyName ) && owningType.isReferenceToPrimaryKey();
}
FromElement addFromElement() throws SemanticException {
final FromClause parentFromClause = fromClause.getParentFromClause();
if ( parentFromClause != null ) {
// Look up class name using the first identifier in the path.
final String pathAlias = PathHelper.getAlias( path );
final FromElement parentFromElement = parentFromClause.getFromElement( pathAlias );
if ( parentFromElement != null ) {
return createFromElementInSubselect( path, pathAlias, parentFromElement, classAlias );
}
}
final EntityPersister entityPersister = fromClause.getSessionFactoryHelper().requireClassPersister( path );
final FromElement elem = createAndAddFromElement(
path,
classAlias,
entityPersister,
(EntityType) ( (Queryable) entityPersister ).getType(),
null
);
// Add to the query spaces.
fromClause.getWalker().addQuerySpaces( entityPersister.getQuerySpaces() );
return elem;
}
protected void initIdentifierPropertyPaths(
final String path,
final EntityType etype,
final String[] columns,
final Mapping factory) throws MappingException {
Type idtype = etype.getIdentifierOrUniqueKeyType( factory );
String idPropName = etype.getIdentifierOrUniqueKeyPropertyName(factory);
boolean hasNonIdentifierPropertyNamedId = hasNonIdentifierPropertyNamedId( etype, factory );
if ( etype.isReferenceToPrimaryKey() ) {
if ( !hasNonIdentifierPropertyNamedId ) {
String idpath1 = extendPath(path, EntityPersister.ENTITY_ID);
addPropertyPath(idpath1, idtype, columns, null);
initPropertyPaths(idpath1, idtype, columns, null, factory);
}
}
if (idPropName!=null) {
String idpath2 = extendPath(path, idPropName);
addPropertyPath(idpath2, idtype, columns, null);
initPropertyPaths(idpath2, idtype, columns, null, factory);
}
}
private FromElement createJoin(
String entityClass,
String tableAlias,
JoinSequence joinSequence,
EntityType type,
boolean manyToMany) throws SemanticException {
// origin, path, implied, columns, classAlias,
EntityPersister entityPersister = fromClause.getSessionFactoryHelper().requireClassPersister( entityClass );
FromElement destination = createAndAddFromElement(
entityClass,
classAlias,
entityPersister,
type,
tableAlias
);
return initializeJoin( path, destination, joinSequence, getColumns(), origin, manyToMany );
}
private void determineValueSelectExpressions(QueryableCollection collectionPersister, List selections) {
AliasGenerator aliasGenerator = new LocalAliasGenerator( 1 );
appendSelectExpressions( collectionPersister.getElementColumnNames(), selections, aliasGenerator );
Type valueType = collectionPersister.getElementType();
if ( valueType.isAssociationType() ) {
EntityType valueEntityType = (EntityType) valueType;
Queryable valueEntityPersister = (Queryable) sfi().getEntityPersister(
valueEntityType.getAssociatedEntityName( sfi() )
);
SelectFragment fragment = valueEntityPersister.propertySelectFragmentFragment(
elementTableAlias(),
null,
false
);
appendSelectExpressions( fragment, selections, aliasGenerator );
}
}
private String getElementName(PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
String name;
if ( element.isOneToMany ) {
name = element.alias;
}
else {
Type type = element.elementType;
if ( type.isEntityType() ) { //ie. a many-to-many
String entityName = ( ( EntityType ) type ).getAssociatedEntityName();
name = pathExpressionParser.continueFromManyToMany( entityName, element.elementColumns, q );
}
else {
throw new QueryException( "illegally dereferenced collection element" );
}
}
return name;
}
/**
* Does the mapping, and Hibernate default semantics, specify that
* this association should be fetched by outer joining
*/
protected boolean isJoinedFetchEnabledInMapping(FetchMode config, AssociationType type)
throws MappingException {
if ( !type.isEntityType() && !type.isCollectionType() ) {
return false;
}
else {
if (config==FetchMode.JOIN) return true;
if (config==FetchMode.SELECT) return false;
if ( type.isEntityType() ) {
//TODO: look at the owning property and check that it
// isn't lazy (by instrumentation)
EntityType entityType =(EntityType) type;
EntityPersister persister = getFactory().getEntityPersister( entityType.getAssociatedEntityName() );
return !persister.hasProxy();
}
else {
return false;
}
}
}
/**
* Visit a property value. Dispatch to the
* correct handler for the property type.
* @param value
* @param type
* @throws HibernateException
*/
final Object processValue(Object value, Type type) throws HibernateException {
if ( type.isCollectionType() ) {
//even process null collections
return processCollection( value, (CollectionType) type );
}
else if ( type.isEntityType() ) {
return processEntity( value, (EntityType) type );
}
else if ( type.isComponentType() ) {
return processComponent( value, (AbstractComponentType) type );
}
else {
return null;
}
}
private CompletionStage<Void> checkIdClass(
final EntityPersister persister,
final LoadEvent event,
final LoadEventListener.LoadType loadType,
final Class<?> idClass) {
// we may have the kooky jpa requirement of allowing find-by-id where
// "id" is the "simple pk value" of a dependent objects parent. This
// is part of its generally goofy "derived identity" "feature"
final IdentifierProperty identifierProperty = persister.getEntityMetamodel().getIdentifierProperty();
if ( identifierProperty.isEmbedded() ) {
final EmbeddedComponentType dependentIdType = (EmbeddedComponentType) identifierProperty.getType();
if ( dependentIdType.getSubtypes().length == 1 ) {
final Type singleSubType = dependentIdType.getSubtypes()[0];
if ( singleSubType.isEntityType() ) {
final EntityType dependentParentType = (EntityType) singleSubType;
final SessionFactoryImplementor factory = event.getSession().getFactory();
final Type dependentParentIdType = dependentParentType.getIdentifierOrUniqueKeyType( factory );
if ( dependentParentIdType.getReturnedClass().isInstance( event.getEntityId() ) ) {
// yep that's what we have...
return loadByDerivedIdentitySimplePkValue( event, loadType, persister,
dependentIdType, factory.getMetamodel().entityPersister( dependentParentType.getAssociatedEntityName() )
);
}
}
}
}
throw new TypeMismatchException(
"Provided id of the wrong type for class " + persister.getEntityName() + ". Expected: " + idClass + ", got " + event.getEntityId().getClass() );
}
public void createPropertyRefConstraints(Map persistentClasses) {
if (referencedPropertyName!=null) {
PersistentClass pc = (PersistentClass) persistentClasses.get(getReferencedEntityName() );
Property property = pc.getReferencedProperty( getReferencedPropertyName() );
if (property==null) {
throw new MappingException(
"Could not find property " +
getReferencedPropertyName() +
" on " +
getReferencedEntityName()
);
}
else {
// todo : if "none" another option is to create the ForeignKey object still but to set its #disableCreation flag
if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) {
java.util.List refColumns = new ArrayList();
Iterator iter = property.getColumnIterator();
while ( iter.hasNext() ) {
Column col = (Column) iter.next();
refColumns.add( col );
}
ForeignKey fk = getTable().createForeignKey(
getForeignKeyName(),
getConstraintColumns(),
( (EntityType) getType() ).getAssociatedEntityName(),
getForeignKeyDefinition(),
refColumns
);
fk.setCascadeDeleteEnabled(isCascadeDeleteEnabled() );
}
}
}
}
private void initializeAndAddFromElement(
FromElement element,
String className,
String classAlias,
EntityPersister entityPersister,
EntityType type,
String tableAlias) {
if ( tableAlias == null ) {
AliasGenerator aliasGenerator = fromClause.getAliasGenerator();
tableAlias = aliasGenerator.createName( entityPersister.getEntityName() );
}
element.initializeEntity( fromClause, className, entityPersister, type, classAlias, tableAlias );
}
private void processJoinReturn(NativeSQLQueryJoinReturn fetchReturn) {
String alias = fetchReturn.getAlias();
// if ( alias2Persister.containsKey( alias ) || collectionAliases.contains( alias ) ) {
if ( alias2Persister.containsKey( alias ) || alias2CollectionPersister.containsKey( alias ) ) {
// already been processed...
return;
}
String ownerAlias = fetchReturn.getOwnerAlias();
// Make sure the owner alias is known...
if ( !alias2Return.containsKey( ownerAlias ) ) {
throw new HibernateException( "Owner alias [" + ownerAlias + "] is unknown for alias [" + alias + "]" );
}
// If this return's alias has not been processed yet, do so b4 further processing of this return
if ( !alias2Persister.containsKey( ownerAlias ) ) {
NativeSQLQueryNonScalarReturn ownerReturn = ( NativeSQLQueryNonScalarReturn ) alias2Return.get(ownerAlias);
processReturn( ownerReturn );
}
SQLLoadable ownerPersister = ( SQLLoadable ) alias2Persister.get( ownerAlias );
Type returnType = ownerPersister.getPropertyType( fetchReturn.getOwnerProperty() );
if ( returnType.isCollectionType() ) {
String role = ownerPersister.getEntityName() + '.' + fetchReturn.getOwnerProperty();
addCollection( role, alias, fetchReturn.getPropertyResultsMap() );
// collectionOwnerAliases.add( ownerAlias );
}
else if ( returnType.isEntityType() ) {
EntityType eType = ( EntityType ) returnType;
String returnEntityName = eType.getAssociatedEntityName();
SQLLoadable persister = getSQLLoadable( returnEntityName );
addPersister( alias, fetchReturn.getPropertyResultsMap(), persister );
}
}
private boolean isOneToOne() {
if ( joinableType.isEntityType() ) {
EntityType etype = (EntityType) joinableType;
return etype.isOneToOne() /*&& etype.isReferenceToPrimaryKey()*/;
}
else {
return false;
}
}
public ExpandingEntityQuerySpace makeEntityQuerySpace(
ExpandingQuerySpace lhsQuerySpace,
AssociationAttributeDefinition attribute,
String querySpaceUid,
FetchStrategy fetchStrategy) {
final EntityType fetchedType = (EntityType) attribute.getType();
final EntityPersister fetchedPersister = attribute.toEntityDefinition().getEntityPersister();
if ( fetchedPersister == null ) {
throw new WalkingException(
String.format(
"Unable to locate EntityPersister [%s] for fetch [%s]",
fetchedType.getAssociatedEntityName(),
attribute.getName()
)
);
}
// TODO: Queryable.isMultiTable() may be more broad than it needs to be...
final boolean isMultiTable = Queryable.class.cast( fetchedPersister ).isMultiTable();
final boolean required = lhsQuerySpace.canJoinsBeRequired() && !isMultiTable && !attribute.isNullable();
return makeEntityQuerySpace(
lhsQuerySpace,
fetchedPersister,
attribute.getName(),
(EntityType) attribute.getType(),
querySpaceUid,
required,
shouldIncludeJoin( fetchStrategy )
);
}
public ExpandingEntityQuerySpace makeEntityQuerySpace(
ExpandingQuerySpace lhsQuerySpace,
EntityPersister fetchedPersister,
String attributeName,
EntityType attributeType,
String querySpaceUid,
boolean required,
boolean shouldIncludeJoin) {
final ExpandingEntityQuerySpace rhs = lhsQuerySpace.getExpandingQuerySpaces().makeEntityQuerySpace(
querySpaceUid,
fetchedPersister,
required
);
if ( shouldIncludeJoin ) {
final JoinDefinedByMetadata join = JoinHelper.INSTANCE.createEntityJoin(
lhsQuerySpace,
attributeName,
rhs,
required,
attributeType,
fetchedPersister.getFactory()
);
lhsQuerySpace.addJoin( join );
}
return rhs;
}
private EntityLoader createUniqueKeyLoader(Type uniqueKeyType, String[] columns, Map enabledFilters) {
if ( uniqueKeyType.isEntityType() ) {
String className = ( ( EntityType ) uniqueKeyType ).getAssociatedEntityName();
uniqueKeyType = getFactory().getEntityPersister( className ).getIdentifierType();
}
return new EntityLoader( this, columns, uniqueKeyType, 1, LockMode.NONE, getFactory(), enabledFilters );
}
public void noCascade(
EventSource session,
Object child,
Object parent,
EntityPersister persister,
int propertyIndex) {
if ( child == null ) {
return;
}
Type type = persister.getPropertyTypes()[propertyIndex];
if ( type.isEntityType() ) {
String childEntityName = ( ( EntityType ) type ).getAssociatedEntityName( session.getFactory() );
if ( ! isInManagedState( child, session )
&& ! ( child instanceof HibernateProxy ) //a proxy cannot be transient and it breaks ForeignKeys.isTransient
&& ForeignKeys.isTransient( childEntityName, child, null, session ) ) {
String parentEntiytName = persister.getEntityName();
String propertyName = persister.getPropertyNames()[propertyIndex];
throw new TransientObjectException(
"object references an unsaved transient instance - " +
"save the transient instance before flushing: " +
parentEntiytName + "." + propertyName + " -> " + childEntityName
);
}
}
}