下面列出了javax.persistence.Embedded#org.hibernate.mapping.PersistentClass 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
private boolean determineCanReadFromCache(PersistentClass persistentClass, EntityDataAccess cacheAccessStrategy) {
if ( cacheAccessStrategy == null ) {
return false;
}
if ( persistentClass.isCached() ) {
return true;
}
final Iterator<Subclass> subclassIterator = persistentClass.getSubclassIterator();
while ( subclassIterator.hasNext() ) {
final Subclass subclass = subclassIterator.next();
if ( subclass.isCached() ) {
return true;
}
}
return false;
}
@PostConstruct
public void init() throws ClassNotFoundException
{
final Configuration configuration = annotationSessionFactory
.getConfiguration();
final ReflectionManager reflectionManager = configuration
.getReflectionManager();
final Iterator<PersistentClass> classMappings = configuration
.getClassMappings();
while (classMappings.hasNext())
{
entityCallbackHandler.add(reflectionManager.classForName(
classMappings.next().getClassName(), this.getClass()),
reflectionManager);
}
}
private void associateSubclassNamesToSubclassTableIndexes(
PersistentClass persistentClass,
Set<String> classNames,
String[][] mapping,
SessionFactoryImplementor factory) {
final String tableName = persistentClass.getTable().getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
);
associateSubclassNamesToSubclassTableIndex( tableName, classNames, mapping );
Iterator itr = persistentClass.getJoinIterator();
while ( itr.hasNext() ) {
final Join join = (Join) itr.next();
final String secondaryTableName = join.getTable().getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName()
);
associateSubclassNamesToSubclassTableIndex( secondaryTableName, classNames, mapping );
}
}
@Override
public void addEntityBinding(PersistentClass persistentClass) throws DuplicateMappingException {
final String entityName = persistentClass.getEntityName();
if ( entityBindingMap.containsKey( entityName ) ) {
throw new DuplicateMappingException( DuplicateMappingException.Type.ENTITY, entityName );
}
entityBindingMap.put( entityName, persistentClass );
final AccessType accessType = AccessType.fromExternalName( persistentClass.getCacheConcurrencyStrategy() );
if ( accessType != null ) {
if ( persistentClass.isCached() ) {
locateCacheRegionConfigBuilder( persistentClass.getRootClass().getCacheRegionName() ).addEntityConfig(
persistentClass,
accessType
);
}
if ( persistentClass.hasNaturalId() && persistentClass instanceof RootClass && persistentClass.getNaturalIdCacheRegionName() != null ) {
locateCacheRegionConfigBuilder( persistentClass.getNaturalIdCacheRegionName() ).addNaturalIdConfig(
(RootClass) persistentClass,
accessType
);
}
}
}
public static EntityPersister createClassPersister(
PersistentClass model,
CacheConcurrencyStrategy cache,
SessionFactoryImplementor factory,
Mapping cfg)
throws HibernateException {
Class persisterClass = model.getEntityPersisterClass();
if (persisterClass==null || persisterClass==SingleTableEntityPersister.class) {
return new SingleTableEntityPersister(model, cache, factory, cfg);
}
else if (persisterClass==JoinedSubclassEntityPersister.class) {
return new JoinedSubclassEntityPersister(model, cache, factory, cfg);
}
else if (persisterClass==UnionSubclassEntityPersister.class) {
return new UnionSubclassEntityPersister(model, cache, factory, cfg);
}
else {
return create(persisterClass, model, cache, factory, cfg);
}
}
public void linkValueUsingDefaultColumnNaming(
Column referencedColumn,
PersistentClass referencedEntity,
SimpleValue value) {
String logicalReferencedColumn = getBuildingContext().getMetadataCollector().getLogicalColumnName(
referencedEntity.getTable(),
referencedColumn.getQuotedName()
);
String columnName = buildDefaultColumnName( referencedEntity, logicalReferencedColumn );
//yuk side effect on an implicit column
setLogicalColumnName( columnName );
setReferencedColumn( logicalReferencedColumn );
initMappingColumn(
columnName,
null, referencedColumn.getLength(),
referencedColumn.getPrecision(),
referencedColumn.getScale(),
getMappingColumn() != null ? getMappingColumn().isNullable() : false,
referencedColumn.getSqlType(),
getMappingColumn() != null ? getMappingColumn().isUnique() : false,
false
);
linkWithValue( value );
}
private void createIndexBackRef(
MappingDocument mappingDocument,
IndexedPluralAttributeSource pluralAttributeSource,
IndexedCollection collectionBinding) {
if ( collectionBinding.isOneToMany()
&& !collectionBinding.getKey().isNullable()
&& !collectionBinding.isInverse() ) {
final String entityName = ( (OneToMany) collectionBinding.getElement() ).getReferencedEntityName();
final PersistentClass referenced = mappingDocument.getMetadataCollector().getEntityBinding( entityName );
final IndexBackref ib = new IndexBackref();
ib.setName( '_' + collectionBinding.getOwnerEntityName() + "." + pluralAttributeSource.getName() + "IndexBackref" );
ib.setUpdateable( false );
ib.setSelectable( false );
ib.setCollectionRole( collectionBinding.getRole() );
ib.setEntityName( collectionBinding.getOwner().getEntityName() );
ib.setValue( collectionBinding.getIndex() );
referenced.addProperty( ib );
}
}
private static void bindPojoRepresentation(Element node, PersistentClass entity,
Mappings mappings, java.util.Map metaTags) {
String className = getClassName( node.attribute( "name" ), mappings );
String proxyName = getClassName( node.attribute( "proxy" ), mappings );
entity.setClassName( className );
if ( proxyName != null ) {
entity.setProxyInterfaceName( proxyName );
entity.setLazy( true );
}
else if ( entity.isLazy() ) {
entity.setProxyInterfaceName( className );
}
Element tuplizer = locateTuplizerDefinition( node, EntityMode.POJO );
if ( tuplizer != null ) {
entity.addTuplizer( EntityMode.POJO, tuplizer.attributeValue( "class" ) );
}
}
@Override
protected IdTableInfoImpl buildIdTableInfo(
PersistentClass entityBinding,
Table idTable,
JdbcServices jdbcServices,
MetadataImplementor metadata,
PreparationContextImpl context) {
final String renderedName = jdbcServices.getJdbcEnvironment().getQualifiedObjectNameFormatter().format(
idTable.getQualifiedTableName(),
jdbcServices.getJdbcEnvironment().getDialect()
);
context.creationStatements.add( buildIdTableCreateStatement( idTable, jdbcServices, metadata ) );
if ( dropIdTables ) {
context.dropStatements.add( buildIdTableDropStatement( idTable, jdbcServices ) );
}
return new IdTableInfoImpl( renderedName );
}
private EntityMetamodel getDeclarerEntityMetamodel(AbstractIdentifiableType<?> ownerType) {
final Type.PersistenceType persistenceType = ownerType.getPersistenceType();
if ( persistenceType == Type.PersistenceType.ENTITY ) {
return context.getSessionFactory()
.getMetamodel()
.entityPersister( ownerType.getTypeName() )
.getEntityMetamodel();
}
else if ( persistenceType == Type.PersistenceType.MAPPED_SUPERCLASS ) {
PersistentClass persistentClass =
context.getPersistentClassHostingProperties( (MappedSuperclassTypeImpl<?>) ownerType );
return context.getSessionFactory()
.getMetamodel()
.entityPersister( persistentClass.getClassName() )
.getEntityMetamodel();
}
else {
throw new AssertionFailure( "Cannot get the metamodel for PersistenceType: " + persistenceType );
}
}
@Override
public org.hibernate.type.Type getIdentifierType(String entityName) throws MappingException {
final PersistentClass pc = entityBindingMap.get( entityName );
if ( pc == null ) {
throw new MappingException( "persistent class not known: " + entityName );
}
return pc.getIdentifier().getType();
}
/**
* 构造Hibernate的乐观锁
*/
private void handleVersion(Property prop, PersistentClass pclazz) {
if (!(pclazz instanceof RootClass)) {
throw new AnnotationException(
"Unable to define/override @Version on a subclass: "
+ pclazz.getEntityName());
}
RootClass root = (RootClass) pclazz;
root.setVersion(prop);
root.setDeclaredVersion(prop);
root.setOptimisticLockStyle(OptimisticLockStyle.VERSION);
}
/**
* Generates the attribute representation of the identifier for a given entity mapping.
*
* @param mappedEntity The mapping definition of the entity.
* @param generator The identifier value generator to use for this identifier.
*
* @return The appropriate IdentifierProperty definition.
*/
public static IdentifierProperty buildIdentifierAttribute(
PersistentClass mappedEntity,
IdentifierGenerator generator) {
String mappedUnsavedValue = mappedEntity.getIdentifier().getNullValue();
Type type = mappedEntity.getIdentifier().getType();
Property property = mappedEntity.getIdentifierProperty();
IdentifierValue unsavedValue = UnsavedValueFactory.getUnsavedIdentifierValue(
mappedUnsavedValue,
getGetter( property ),
type,
getConstructor( mappedEntity )
);
if ( property == null ) {
// this is a virtual id property...
return new IdentifierProperty(
type,
mappedEntity.hasEmbeddedIdentifier(),
mappedEntity.hasIdentifierMapper(),
unsavedValue,
generator
);
}
else {
return new IdentifierProperty(
property.getName(),
type,
mappedEntity.hasEmbeddedIdentifier(),
unsavedValue,
generator
);
}
}
private void applyCacheSettings(Configuration configuration) {
if ( settings.getCacheConcurrencyStrategy() != null ) {
Iterator iter = configuration.getClassMappings();
while ( iter.hasNext() ) {
PersistentClass clazz = (PersistentClass) iter.next();
Iterator props = clazz.getPropertyClosureIterator();
boolean hasLob = false;
while ( props.hasNext() ) {
Property prop = (Property) props.next();
if ( prop.getValue().isSimpleValue() ) {
String type = ( ( SimpleValue ) prop.getValue() ).getTypeName();
if ( "blob".equals(type) || "clob".equals(type) ) {
hasLob = true;
}
if ( Blob.class.getName().equals(type) || Clob.class.getName().equals(type) ) {
hasLob = true;
}
}
}
if ( !hasLob && !clazz.isInherited() && settings.overrideCacheStrategy() ) {
configuration.setCacheConcurrencyStrategy( clazz.getEntityName(), settings.getCacheConcurrencyStrategy() );
}
}
iter = configuration.getCollectionMappings();
while ( iter.hasNext() ) {
Collection coll = (Collection) iter.next();
configuration.setCollectionCacheConcurrencyStrategy( coll.getRole(), settings.getCacheConcurrencyStrategy() );
}
}
}
public ReactiveJoinedSubclassEntityPersister(
PersistentClass persistentClass,
EntityDataAccess cacheAccessStrategy,
NaturalIdDataAccess naturalIdRegionAccessStrategy,
PersisterCreationContext creationContext) throws HibernateException {
super( persistentClass, cacheAccessStrategy, naturalIdRegionAccessStrategy, creationContext );
}
private static Constructor getConstructor(PersistentClass persistentClass) {
if ( persistentClass == null || !persistentClass.hasPojoRepresentation() ) {
return null;
}
try {
return ReflectHelper.getDefaultConstructor( persistentClass.getMappedClass() );
}
catch (Throwable t) {
return null;
}
}
/**
* Gets the Spanner {@link Table} by entity class.
*/
public static Table getTable(Class<?> entityClass, Metadata metadata) {
PersistentClass pc = metadata.getEntityBinding(entityClass.getCanonicalName());
if (pc != null) {
return pc.getTable();
}
throw new IllegalArgumentException(
String.format("Could not find table for entity class %s.", entityClass.getName()));
}
public static ProxyDefinitions createFromMetadata(Metadata storeableMetadata, PreGeneratedProxies preGeneratedProxies) {
//Check upfront for any need across all metadata: would be nice to avoid initializing the Bytecode provider.
LazyBytecode lazyBytecode = new LazyBytecode();
if (needAnyProxyDefinitions(storeableMetadata)) {
final HashMap<Class<?>, ProxyClassDetailsHolder> proxyDefinitionMap = new HashMap<>();
try {
for (PersistentClass persistentClass : storeableMetadata.getEntityBindings()) {
if (needsProxyGeneration(persistentClass)) {
final Class mappedClass = persistentClass.getMappedClass();
final Class proxyClassDefinition = generateProxyClass(persistentClass, lazyBytecode,
preGeneratedProxies);
if (proxyClassDefinition == null) {
continue;
}
final boolean overridesEquals = ReflectHelper.overridesEquals(mappedClass);
try {
proxyDefinitionMap.put(mappedClass,
new ProxyClassDetailsHolder(overridesEquals, proxyClassDefinition.getConstructor()));
} catch (NoSuchMethodException e) {
throw new HibernateException(
"Failed to generate Enhanced Proxy: default constructor is missing for entity '"
+ mappedClass.getName() + "'. Please add a default constructor explicitly.");
}
}
}
} finally {
lazyBytecode.close();
}
return new ProxyDefinitions(proxyDefinitionMap);
} else {
return new ProxyDefinitions(Collections.emptyMap());
}
}
public void testComparator() {
PersistentClass cm = cfg.getClassMapping("org.hibernate.test.legacy.Wicked");
Property property = cm.getProperty("sortedEmployee");
Collection col = (Collection) property.getValue();
assertEquals(col.getComparatorClassName(),"org.hibernate.test.legacy.NonExistingComparator");
}
@SuppressWarnings("unchecked")
public void buildView(Class<?> entityClazz, MetadataFactory mf, T annotation, ApplicationContext context) {
PersistentClass hibernateClass = this.metadata.getEntityBinding(entityClazz.getName());
org.hibernate.mapping.Table ormTable = hibernateClass.getTable();
String tableName = ormTable.getQuotedName();
javax.persistence.Entity entityAnnotation = entityClazz.getAnnotation(javax.persistence.Entity.class);
if (entityAnnotation != null && !entityAnnotation.name().isEmpty()) {
tableName = entityAnnotation.name();
}
javax.persistence.Table tableAnnotation = entityClazz.getAnnotation(javax.persistence.Table.class);
if (tableAnnotation != null && !tableAnnotation.name().isEmpty()) {
tableName = tableAnnotation.name();
}
Table view = mf.addTable(tableName);
view.setVirtual(true);
view.setSupportsUpdate(true);
onTableCreate(view, mf, entityClazz, annotation);
Iterator<org.hibernate.mapping.Column> it = ormTable.getColumnIterator();
while (it.hasNext()) {
org.hibernate.mapping.Column ormColumn = it.next();
FieldInfo attribute = getAttributeField(entityClazz, hibernateClass, ormColumn.getName(), new FieldInfo());
// .. parent is used in the graph like structures, for now in json table.
addColumn(ormTable, ormColumn, attribute.path, attribute.field, view, mf, !it.hasNext(), annotation);
}
addPrimaryKey(ormTable, view, mf);
addForeignKeys(ormTable, view, mf);
addIndexKeys(ormTable, view, mf);
onFinish(view, mf, entityClazz, annotation, context);
}
List<Resource> generatedScripts() {
List<Resource> resources = Collections.emptyList();
for (PersistentClass clazz : metadata.getEntityBindings()) {
org.hibernate.mapping.Table ormTable = clazz.getTable();
String tableName = ormTable.getQuotedName();
if (this.schema.getTable(tableName) != null) {
org.hibernate.mapping.Column c = new org.hibernate.mapping.Column(
RedirectionSchemaBuilder.ROW_STATUS_COLUMN);
c.setSqlTypeCode(TypeFacility.getSQLTypeFromRuntimeType(Integer.class));
c.setSqlType(JDBCSQLTypeInfo.getTypeName(TypeFacility.getSQLTypeFromRuntimeType(Integer.class)));
ormTable.addColumn(c);
ormTable.setName(tableName + TeiidConstants.REDIRECTED_TABLE_POSTFIX);
}
}
List<String> statements = createScript(metadata, dialect, true);
StringBuilder sb = new StringBuilder();
for (String s : statements) {
// we have no need for sequences in the redirected scenario, they are fed from
// other side.
if (s.startsWith("drop sequence") || s.startsWith("create sequence")) {
continue;
}
sb.append(s).append(";\n");
}
logger.debug("Redirected Schema:\n" + sb.toString());
resources = Arrays.asList(new ByteArrayResource(sb.toString().getBytes()));
return resources;
}
public ClassPropertyHolder(
PersistentClass persistentClass,
XClass entityXClass,
Map<String, Join> joins,
MetadataBuildingContext context,
Map<XClass, InheritanceState> inheritanceStatePerClass) {
super( persistentClass.getEntityName(), null, entityXClass, context );
this.persistentClass = persistentClass;
this.joins = joins;
this.inheritanceStatePerClass = inheritanceStatePerClass;
this.attributeConversionInfoMap = buildAttributeConversionInfoMap( entityXClass );
}
@Override
public String getIdentifierPropertyName(String entityName) throws MappingException {
final PersistentClass pc = entityBindingMap.get( entityName );
if ( pc == null ) {
throw new MappingException( "persistent class not known: " + entityName );
}
if ( !pc.hasIdentifierProperty() ) {
return null;
}
return pc.getIdentifierProperty().getName();
}
protected void secondPassCompileForeignKeys(Table table, Set done) throws MappingException {
table.createForeignKeys();
Iterator iter = table.getForeignKeyIterator();
while ( iter.hasNext() ) {
ForeignKey fk = (ForeignKey) iter.next();
if ( !done.contains( fk ) ) {
done.add( fk );
final String referencedEntityName = fk.getReferencedEntityName();
if ( referencedEntityName == null ) {
throw new MappingException(
"An association from the table " +
fk.getTable().getName() +
" does not specify the referenced entity"
);
}
if ( log.isDebugEnabled() ) {
log.debug( "resolving reference to class: " + referencedEntityName );
}
PersistentClass referencedClass = (PersistentClass) classes.get( referencedEntityName );
if ( referencedClass == null ) {
throw new MappingException(
"An association from the table " +
fk.getTable().getName() +
" refers to an unmapped class: " +
referencedEntityName
);
}
if ( referencedClass.isJoinedSubclass() ) {
secondPassCompileForeignKeys( referencedClass.getSuperclass().getTable(), done );
}
fk.setReferencedTable( referencedClass.getTable() );
fk.alignColumns();
}
}
}
@Override
protected QualifiedTableName determineIdTableName(
JdbcEnvironment jdbcEnvironment,
PersistentClass entityBinding) {
return new QualifiedTableName(
catalog,
schema,
super.determineIdTableName( jdbcEnvironment, entityBinding ).getTableName()
);
}
private static void applyDDL(
String prefix,
PersistentClass persistentClass,
Class<?> clazz,
ValidatorFactory factory,
Set<Class<?>> groups,
boolean activateNotNull,
Dialect dialect) {
final BeanDescriptor descriptor = factory.getValidator().getConstraintsForClass( clazz );
//no bean level constraints can be applied, go to the properties
for ( PropertyDescriptor propertyDesc : descriptor.getConstrainedProperties() ) {
Property property = findPropertyByName( persistentClass, prefix + propertyDesc.getPropertyName() );
boolean hasNotNull;
if ( property != null ) {
hasNotNull = applyConstraints(
propertyDesc.getConstraintDescriptors(), property, propertyDesc, groups, activateNotNull, dialect
);
if ( property.isComposite() && propertyDesc.isCascaded() ) {
Class<?> componentClass = ( (Component) property.getValue() ).getComponentClass();
/*
* we can apply not null if the upper component let's us activate not null
* and if the property is not null.
* Otherwise, all sub columns should be left nullable
*/
final boolean canSetNotNullOnColumns = activateNotNull && hasNotNull;
applyDDL(
prefix + propertyDesc.getPropertyName() + ".",
persistentClass, componentClass, factory, groups,
canSetNotNullOnColumns,
dialect
);
}
//FIXME add collection of components
}
}
}
private static PersistentClass getSuperclass(Mappings mappings, Element subnode)
throws MappingException {
String extendsName = subnode.attributeValue( "extends" );
PersistentClass superModel = mappings.getClass( extendsName );
if ( superModel == null ) {
String qualifiedExtendsName = getClassName( extendsName, mappings );
superModel = mappings.getClass( qualifiedExtendsName );
}
if ( superModel == null ) {
throw new MappingException( "Cannot extend unmapped class " + extendsName );
}
return superModel;
}
protected ProxyFactory buildProxyFactoryInternal(
PersistentClass persistentClass,
Getter idGetter,
Setter idSetter) {
// TODO : YUCK!!! fix after HHH-1907 is complete
return Environment.getBytecodeProvider().getProxyFactoryFactory().buildProxyFactory( getFactory() );
// return getFactory().getSettings().getBytecodeProvider().getProxyFactoryFactory().buildProxyFactory();
}
public static BytecodeEnhancementMetadata from(PersistentClass persistentClass) {
final Class mappedClass = persistentClass.getMappedClass();
final boolean enhancedForLazyLoading = PersistentAttributeInterceptable.class.isAssignableFrom( mappedClass );
final LazyAttributesMetadata lazyAttributesMetadata = enhancedForLazyLoading
? LazyAttributesMetadata.from( persistentClass )
: LazyAttributesMetadata.nonEnhanced( persistentClass.getEntityName() );
return new BytecodeEnhancementMetadataPojoImpl(
persistentClass.getEntityName(),
mappedClass,
enhancedForLazyLoading,
lazyAttributesMetadata
);
}
public void doSecondPass(Map persistentClasses) throws MappingException {
PersistentClass referencedEntity = (PersistentClass) persistentClasses.get( referencedEntityName );
if ( referencedEntity == null ) {
throw new AnnotationException(
"Unknown entity name: " + referencedEntityName
);
}
TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit(
referencedEntity,
referencedEntity.getKey().getColumnIterator(),
columns,
value);
}