下面列出了怎么用org.hibernate.persister.entity.AbstractEntityPersister的API类实例代码及写法,或者点击链接到github查看源代码。
public static EntityIdentifierDefinition buildSimpleEncapsulatedIdentifierDefinition(final AbstractEntityPersister entityPersister) {
return new EncapsulatedEntityIdentifierDefinition() {
private final AttributeDefinitionAdapter attr = new AttributeDefinitionAdapter( entityPersister);
@Override
public AttributeDefinition getAttributeDefinition() {
return attr;
}
@Override
public boolean isEncapsulated() {
return true;
}
@Override
public EntityDefinition getEntityDefinition() {
return entityPersister;
}
};
}
public static EntityIdentifierDefinition buildEncapsulatedCompositeIdentifierDefinition(
final AbstractEntityPersister entityPersister) {
return new EncapsulatedEntityIdentifierDefinition() {
private final CompositionDefinitionAdapter compositionDefinition = new CompositionDefinitionAdapter( entityPersister );
@Override
public AttributeDefinition getAttributeDefinition() {
return compositionDefinition;
}
@Override
public boolean isEncapsulated() {
return true;
}
@Override
public EntityDefinition getEntityDefinition() {
return entityPersister;
}
};
}
public static String getColumnNameFromMetaModel(Attribute column) {
String columnName = null;
try {
if (isEclipseLinkOnClasspath()) {
columnName = ((AttributeImpl) column).getMapping().getField().getName();
} else if (isHibernateOnClasspath() && isEntityManagerActive()) {
AbstractEntityPersister entityMetadata = (AbstractEntityPersister) em().getEntityManagerFactory().unwrap(SessionFactory.class).getClassMetadata(column.getJavaMember().getDeclaringClass());
columnName = entityMetadata.getPropertyColumnNames(column.getName())[0];
}
} catch (Exception e) {
LOGGER.error("Could not extract database column name from column {} and type {}", column.getName(), column.getDeclaringType().getJavaType().getName(), e);
}
if (columnName == null) {
columnName = convertCase(column.getName(), config);
}
return columnName;
}
private static void modifyConstraints(SessionFactoryImpl sessionFactoryImpl) {
ClassMetadata classMetadata = sessionFactoryImpl.getClassMetadata(MCRCategoryImpl.class);
AbstractEntityPersister aep = (AbstractEntityPersister) classMetadata;
String qualifiedTableName = aep.getTableName();
try (Session session = sessionFactoryImpl.openSession()) {
session.doWork(connection -> {
String updateStmt = Stream.of("ClassLeftUnique", "ClassRightUnique")
.flatMap(idx -> Stream.of("drop constraint if exists " + idx,
String.format(Locale.ROOT, "add constraint %s unique (%s) deferrable initially deferred", idx,
getUniqueColumns(MCRCategoryImpl.class, idx))))
.collect(Collectors.joining(", ", getAlterTableString(connection) + qualifiedTableName + " ", ""));
try (Statement stmt = connection.createStatement()) {
LogManager.getLogger().info("Fixing PostgreSQL Schema for {}:\n{}", qualifiedTableName, updateStmt);
stmt.execute(updateStmt);
}
});
}
}
/**
* 获取所有数据表
*
* @return
*/
public List<DBTable> getAllDbTableName() {
List<DBTable> resultList = new ArrayList<DBTable>();
SessionFactory factory = getSession().getSessionFactory();
Map<String, ClassMetadata> metaMap = factory.getAllClassMetadata();
for (String key : (Set<String>) metaMap.keySet()) {
DBTable dbTable = new DBTable();
AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
.get(key);
dbTable.setTableName(classMetadata.getTableName());
dbTable.setEntityName(classMetadata.getEntityName());
Class<?> c;
try {
c = Class.forName(key);
JeecgEntityTitle t = c.getAnnotation(JeecgEntityTitle.class);
dbTable.setTableTitle(t != null ? t.name() : "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
resultList.add(dbTable);
}
return resultList;
}
/**
* 获取所有数据表
*
* @return
*/
public List<DBTable> getAllDbTableName() {
List<DBTable> resultList = new ArrayList<DBTable>();
SessionFactory factory = getSession().getSessionFactory();
Map<String, ClassMetadata> metaMap = factory.getAllClassMetadata();
for (String key : (Set<String>) metaMap.keySet()) {
DBTable dbTable = new DBTable();
AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
.get(key);
dbTable.setTableName(classMetadata.getTableName());
dbTable.setEntityName(classMetadata.getEntityName());
Class<?> c;
try {
c = Class.forName(key);
JeecgEntityTitle t = c.getAnnotation(JeecgEntityTitle.class);
dbTable.setTableTitle(t != null ? t.name() : "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
resultList.add(dbTable);
}
return resultList;
}
private void visitEntityDefinition(EntityDefinition entityDefinition) {
strategy.startingEntity( entityDefinition );
AbstractEntityPersister persister = (AbstractEntityPersister) entityDefinition.getEntityPersister();
visitIdentifierDefinition( entityDefinition.getEntityKeyDefinition() );
visitAttributes( entityDefinition, persister);
strategy.finishingEntity( entityDefinition );
}
private void visitAttributes(AttributeSource attributeSource, AbstractEntityPersister sourcePersister) {
final Iterable<AttributeDefinition> attributeDefinitions = attributeSource.getAttributes();
if ( attributeDefinitions == null ) {
return;
}
for ( AttributeDefinition attributeDefinition : attributeDefinitions ) {
visitAttributeDefinition( attributeDefinition, sourcePersister);
}
}
/**
* Get composite ID sub-attribute definitions.
*
* @param entityPersister - the entity persister.
*
* @return composite ID sub-attribute definitions.
*/
public static Iterable<AttributeDefinition> getIdentifierSubAttributes(AbstractEntityPersister entityPersister) {
return getSingularSubAttributes(
entityPersister,
entityPersister,
(CompositeType) entityPersister.getIdentifierType(),
entityPersister.getTableName(),
entityPersister.getRootTableIdentifierColumnNames()
);
}
private boolean isSubclassAliasDereferenced(Join join, String withClauseFragment) {
if ( join.getJoinable() instanceof AbstractEntityPersister ) {
AbstractEntityPersister persister = (AbstractEntityPersister) join.getJoinable();
int subclassTableSpan = persister.getSubclassTableSpan();
for ( int j = 1; j < subclassTableSpan; j++ ) {
String subclassAlias = AbstractEntityPersister.generateTableAlias( join.getAlias(), j );
if ( isAliasDereferenced( withClauseFragment, subclassAlias ) ) {
return true;
}
}
}
return false;
}
@Override
public String getAlias(String table) {
if ( table == null ) {
return rootAlias;
}
else {
return AbstractEntityPersister.generateTableAlias(
rootAlias,
AbstractEntityPersister.getTableId( table, tables )
);
}
}
private void loadSystemTableList(SessionFactory sessionFactory) {
Map<String, ClassMetadata> allClassMetadata = sessionFactory.getAllClassMetadata();
allClassMetadata.forEach((key, value) -> {
AbstractEntityPersister abstractEntityPersister = (AbstractEntityPersister) value;
SYSTEM_TABLE_LIST.add(abstractEntityPersister.getTableName());
});
}
public String getColumn(String model, String field) {
SessionImpl sessionImpl = (SessionImpl) JPA.em().getDelegate();
@SuppressWarnings("deprecation")
AbstractEntityPersister aep =
((AbstractEntityPersister)
sessionImpl.getSession().getSessionFactory().getClassMetadata(model));
String[] columns = aep.getPropertyColumnNames(field);
if (columns != null && columns.length > 0) {
return columns[0];
}
return null;
}
private void addJoins(
Join join,
JoinFragment joinFragment,
Joinable joinable,
String joinConditions) {
final String rhsTableAlias = aliasResolutionContext.resolveSqlTableAliasFromQuerySpaceUid(
join.getRightHandSide().getUid()
);
if ( StringHelper.isEmpty( rhsTableAlias ) ) {
throw new IllegalStateException( "Join's RHS table alias cannot be empty" );
}
final String lhsTableAlias = aliasResolutionContext.resolveSqlTableAliasFromQuerySpaceUid(
join.getLeftHandSide().getUid()
);
if ( lhsTableAlias == null ) {
throw new IllegalStateException( "QuerySpace with that UID was not yet registered in the AliasResolutionContext" );
}
String otherConditions = join.getAnyAdditionalJoinConditions( rhsTableAlias );
if ( !StringHelper.isEmpty( otherConditions ) && !StringHelper.isEmpty( joinConditions ) ) {
otherConditions += " and " + joinConditions;
}
else if ( !StringHelper.isEmpty( joinConditions ) ) {
otherConditions = joinConditions;
}
// add join fragments from the collection table -> element entity table ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
final String additionalJoinConditions = resolveAdditionalJoinCondition(
rhsTableAlias,
otherConditions,
joinable,
getJoinedAssociationTypeOrNull( join )
);
String[] joinColumns = join.resolveAliasedLeftHandSideJoinConditionColumns( lhsTableAlias );
if ( joinColumns.length == 0 ) {
// When no columns are available, this is a special join that involves multiple subtypes
AbstractEntityPersister persister = (AbstractEntityPersister) ( (EntityQuerySpace) join.getLeftHandSide() ).getEntityPersister();
String[][] polyJoinColumns = persister.getPolymorphicJoinColumns(
lhsTableAlias,
( (JoinDefinedByMetadata) join ).getJoinedPropertyName()
);
joinFragment.addJoin(
joinable.getTableName(),
rhsTableAlias,
polyJoinColumns,
join.resolveNonAliasedRightHandSideJoinConditionColumns(),
join.isRightHandSideRequired() ? JoinType.INNER_JOIN : JoinType.LEFT_OUTER_JOIN,
additionalJoinConditions
);
}
else {
joinFragment.addJoin(
joinable.getTableName(),
rhsTableAlias,
joinColumns,
join.resolveNonAliasedRightHandSideJoinConditionColumns(),
join.isRightHandSideRequired() ? JoinType.INNER_JOIN : JoinType.LEFT_OUTER_JOIN,
additionalJoinConditions
);
}
joinFragment.addJoins(
joinable.fromJoinFragment( rhsTableAlias, false, true ),
joinable.whereJoinFragment( rhsTableAlias, false, true )
);
}
private void visitAttributeDefinition(AttributeDefinition attributeDefinition, AbstractEntityPersister sourcePersister) {
final PropertyPath subPath = currentPropertyPath.append( attributeDefinition.getName() );
log.debug( "Visiting attribute path : " + subPath.getFullPath() );
if ( attributeDefinition.getType().isAssociationType() ) {
final AssociationAttributeDefinition associationAttributeDefinition =
(AssociationAttributeDefinition) attributeDefinition;
final AssociationKey associationKey = associationAttributeDefinition.getAssociationKey();
if ( isDuplicateAssociationKey( associationKey ) ) {
log.debug( "Property path deemed to be circular : " + subPath.getFullPath() );
strategy.foundCircularAssociation( associationAttributeDefinition );
// EARLY EXIT!!!
return;
}
if ( sourcePersister != null ) {
String[] columns = sourcePersister.toColumns(attributeDefinition.getName());
// Empty columns means that the attribute is not resolvable on this persister
if ( columns.length == 0 ) {
return;
}
}
}
boolean continueWalk = strategy.startingAttribute( attributeDefinition );
if ( continueWalk ) {
final PropertyPath old = currentPropertyPath;
currentPropertyPath = subPath;
try {
final Type attributeType = attributeDefinition.getType();
if ( attributeType.isAssociationType() ) {
visitAssociation( (AssociationAttributeDefinition) attributeDefinition );
}
else if ( attributeType.isComponentType() ) {
visitCompositeDefinition( (CompositionDefinition) attributeDefinition );
}
}
finally {
currentPropertyPath = old;
}
}
strategy.finishingAttribute( attributeDefinition );
}
public static EntityIdentifierDefinition buildNonEncapsulatedCompositeIdentifierDefinition(final AbstractEntityPersister entityPersister) {
return new NonEncapsulatedEntityIdentifierDefinition() {
private final CompositionDefinitionAdapter compositionDefinition = new CompositionDefinitionAdapter( entityPersister );
@Override
public Iterable<AttributeDefinition> getAttributes() {
return compositionDefinition.getAttributes();
}
@Override
public Class getSeparateIdentifierMappingClass() {
return entityPersister.getEntityMetamodel().getIdentifierProperty().hasIdentifierMapper() ?
entityPersister.getEntityMetamodel().getIdentifierProperty().getType().getReturnedClass() :
null;
}
@Override
public boolean isEncapsulated() {
return false;
}
@Override
public EntityDefinition getEntityDefinition() {
return entityPersister;
}
@Override
public Type getCompositeType() {
return entityPersister.getEntityMetamodel().getIdentifierProperty().getType();
}
@Override
public AttributeSource getSource() {
return compositionDefinition;
}
@Override
public String getName() {
// Not sure this is always kosher. See org.hibernate.tuple.entity.EntityMetamodel.hasNonIdentifierPropertyNamedId
return "id";
}
@Override
public CompositeType getType() {
return (CompositeType) getCompositeType();
}
@Override
public boolean isNullable() {
return compositionDefinition.isNullable();
}
};
}
AttributeDefinitionAdapter(AbstractEntityPersister entityPersister) {
this.entityPersister = entityPersister;
}
protected AbstractEntityPersister getEntityPersister() {
return entityPersister;
}
CompositionDefinitionAdapter(AbstractEntityPersister entityPersister) {
super( entityPersister );
}
public void resolve(boolean generateJoin, boolean implicitJoin, String classAlias, AST parent, AST parentPredicate)
throws SemanticException {
// If this dot has already been resolved, stop now.
if ( isResolved() ) {
return;
}
Type propertyType = prepareLhs(); // Prepare the left hand side and get the data type.
if ( parent == null && AbstractEntityPersister.ENTITY_CLASS.equals( propertyName ) ) {
DeprecationLogger.DEPRECATION_LOGGER.logDeprecationOfClassEntityTypeSelector( getLhs().getPath() );
}
// If there is no data type for this node, and we're at the end of the path (top most dot node), then
// this might be a Java constant.
if ( propertyType == null ) {
if ( parent == null ) {
getWalker().getLiteralProcessor().lookupConstant( this );
}
// If the propertyType is null and there isn't a parent, just
// stop now... there was a problem resolving the node anyway.
return;
}
if ( propertyType.isComponentType() ) {
// The property is a component...
checkLhsIsNotCollection();
dereferenceComponent( parent );
initText();
}
else if ( propertyType.isEntityType() ) {
// The property is another class..
checkLhsIsNotCollection();
dereferenceEntity( (EntityType) propertyType, implicitJoin, classAlias, generateJoin, parent, parentPredicate );
initText();
}
else if ( propertyType.isCollectionType() ) {
// The property is a collection...
checkLhsIsNotCollection();
dereferenceCollection( (CollectionType) propertyType, implicitJoin, false, classAlias, parent );
}
else {
// Otherwise, this is a primitive type.
if ( !CollectionProperties.isAnyCollectionProperty( propertyName ) ) {
checkLhsIsNotCollection();
}
dereferenceType = DereferenceType.PRIMITIVE;
initText();
}
setResolved();
}
/**
* Ugh!
*/
@Override
public JoinFragment toJoinFragment(
Map enabledFilters,
boolean includeAllSubclassJoins,
String withClauseFragment) throws MappingException {
final String joinString;
switch ( joinType ) {
case INNER_JOIN:
joinString = " inner join ";
break;
case LEFT_OUTER_JOIN:
joinString = " left outer join ";
break;
case RIGHT_OUTER_JOIN:
joinString = " right outer join ";
break;
case FULL_JOIN:
joinString = " full outer join ";
break;
default:
throw new AssertionFailure( "undefined join type" );
}
final StringBuilder buffer = new StringBuilder();
final AbstractEntityPersister joinable = (AbstractEntityPersister) entityType.getAssociatedJoinable(factory);
buffer.append( joinString );
Set<String> treatAsDeclarations = getTreatAsDeclarations();
final boolean include = includeAllSubclassJoins && isIncluded( entityTableAlias );
String fromFragment = joinable.fromJoinFragment( entityTableAlias, true, include, treatAsDeclarations );
String whereFragment = joinable.whereJoinFragment( entityTableAlias, true, include, treatAsDeclarations );
// We need a table group only when having e.g. a left join of a polymorphic entity
// fromFragment is empty if the entity is non-polymorphic
// Inner joined entity joins can avoid using the table grouping since the condition can be moved to the where clause
boolean renderTableGroup = !fromFragment.isEmpty() && joinType != JoinType.INNER_JOIN;
if ( renderTableGroup ) {
buffer.append( '(' );
}
buffer.append( entityTableText )
.append( ' ' )
.append( entityTableAlias );
if ( renderTableGroup ) {
buffer.append( fromFragment )
.append( ')' );
}
buffer.append( " on " );
final String filters = entityType.getOnCondition(
entityTableAlias,
factory,
enabledFilters,
Collections.<String>emptySet()
);
if ( fromFragment.isEmpty() || renderTableGroup ) {
buffer.append( filters );
if ( withClauseFragment != null ) {
if ( StringHelper.isNotEmpty( filters ) ) {
buffer.append( " and " );
}
buffer.append( withClauseFragment );
}
}
else {
// We know there is a fromFragment and that we shouldn't render a table group
// This means the entity is polymorphic and the entity join is an inner join
// We move the with clause stuff to the where clause but still need to have a valid on condition
buffer.append( "1=1" );
buffer.append( fromFragment );
// Proper capacity to avoid resizing
StringBuilder whereBuffer = new StringBuilder(
10
+ whereFragment.length()
+ filters.length()
+ withClauseFragment.length()
);
whereBuffer.append(whereFragment);
if ( !filters.isEmpty() ) {
whereBuffer.append( " and " );
whereBuffer.append( filters );
}
if ( !withClauseFragment.isEmpty() ) {
whereBuffer.append( " and " );
whereBuffer.append( withClauseFragment );
}
whereFragment = whereBuffer.toString();
}
return new EntityJoinJoinFragment( buffer.toString(), whereFragment );
}
private static String getPropertyColumnName(Class entity, String property, SessionFactory sessionFactory) {
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(entity);
AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata;
String[] columnNames = persister.getPropertyColumnNames(property);
return columnNames[0];
}
/**
* A self-reference of type {@code AbstractEntityPersister}.
*
* @return this object
*/
default AbstractEntityPersister delegate() {
return (AbstractEntityPersister) this;
}