org.hibernate.persister.entity.AbstractEntityPersister Java Examples

The following examples show how to use org.hibernate.persister.entity.AbstractEntityPersister. 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: GenericBaseCommonDao.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 获取所有数据表
 *
 * @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;
}
 
Example #2
Source File: GenericBaseCommonDao.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 获取所有数据表
 * 
 * @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;
}
 
Example #3
Source File: EntityIdentifierDefinitionHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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;
		}
	};
}
 
Example #4
Source File: EntityIdentifierDefinitionHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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;
		}
	};
}
 
Example #5
Source File: MCRHibernateConfigHelper.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
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);
            }
        });
    }
}
 
Example #6
Source File: BuilderUtil.java    From database-rider with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: CompositionSingularSubAttributesHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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()
	);
}
 
Example #8
Source File: FilterSqlService.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
  }
 
Example #9
Source File: DatabaseH2Service.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
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());
    });
}
 
Example #10
Source File: DynamicFilterAliasGenerator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getAlias(String table) {
	if ( table == null ) {
		return rootAlias;
	}
	else {
		return AbstractEntityPersister.generateTableAlias(
				rootAlias,
				AbstractEntityPersister.getTableId( table, tables )
		);
	}
}
 
Example #11
Source File: JoinSequence.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example #12
Source File: MetamodelGraphWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void visitAttributes(AttributeSource attributeSource, AbstractEntityPersister sourcePersister) {
	final Iterable<AttributeDefinition> attributeDefinitions = attributeSource.getAttributes();
	if ( attributeDefinitions == null ) {
		return;
	}
	for ( AttributeDefinition attributeDefinition : attributeDefinitions ) {
		visitAttributeDefinition( attributeDefinition, sourcePersister);
	}
}
 
Example #13
Source File: MetamodelGraphWalker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void visitEntityDefinition(EntityDefinition entityDefinition) {
	strategy.startingEntity( entityDefinition );

	AbstractEntityPersister persister = (AbstractEntityPersister) entityDefinition.getEntityPersister();
	visitIdentifierDefinition( entityDefinition.getEntityKeyDefinition() );
	visitAttributes( entityDefinition, persister);

	strategy.finishingEntity( entityDefinition );
}
 
Example #14
Source File: EntityIdentifierDefinitionHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
CompositionDefinitionAdapter(AbstractEntityPersister entityPersister) {
	super( entityPersister );
}
 
Example #15
Source File: EntityIdentifierDefinitionHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
protected AbstractEntityPersister getEntityPersister() {
	return entityPersister;
}
 
Example #16
Source File: DotNode.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
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();
}
 
Example #17
Source File: EntityJoinFromElement.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 );
}
 
Example #18
Source File: QueryUtil.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
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];
}
 
Example #19
Source File: EntityIdentifierDefinitionHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
AttributeDefinitionAdapter(AbstractEntityPersister entityPersister) {
	this.entityPersister = entityPersister;
}
 
Example #20
Source File: EntityIdentifierDefinitionHelper.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
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();
		}
	};
}
 
Example #21
Source File: MetamodelGraphWalker.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
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 );
}
 
Example #22
Source File: LoadQueryJoinAndFetchProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
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 )
	);
}
 
Example #23
Source File: ReactiveAbstractEntityPersister.java    From hibernate-reactive with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * A self-reference of type {@code AbstractEntityPersister}.
 *
 * @return this object
 */
default AbstractEntityPersister delegate() {
	return (AbstractEntityPersister) this;
}