Java Code Examples for org.hibernate.mapping.PersistentClass#getTable()

The following examples show how to use org.hibernate.mapping.PersistentClass#getTable() . These examples are extracted from open source projects. 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
@Test
public void testEntityToDatabaseBindingMetadata() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();

    for ( PersistentClass persistentClass : metadata.getEntityBindings()) {
        Table table = persistentClass.getTable();
        LOGGER.info( "Entity: {} is mapped to table: {}",
                     persistentClass.getClassName(),
                     table.getName()
        );

        for(Iterator propertyIterator =
                persistentClass.getPropertyIterator(); propertyIterator.hasNext(); ) {
            Property property = (Property) propertyIterator.next();
            for(Iterator columnIterator =
                    property.getColumnIterator(); columnIterator.hasNext(); ) {
                Column column = (Column) columnIterator.next();
                LOGGER.info( "Property: {} is mapped on table column: {} of type: {}",
                             property.getName(),
                             column.getName(),
                             column.getSqlType()
                );
            }
        }
    }
}
 
Example 2
/**
 * 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()));
}
 
Example 3
Source Project: teiid-spring-boot   File: ViewBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 4
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;
}
 
Example 5
@Test
public void givenLegacyJpaImplNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
    String entity = Account.class.getCanonicalName();
    PersistentClass persistentClass = metadata.getEntityBinding(entity);
    Table table = persistentClass.getTable();
    String physicalNameExpected = "Secondary_Email";
    String implicitNameExpected = "defaultEmail";
    String tableNameExpected = "Account";

    String tableNameCreated = table.getName();
    boolean columnNameIsQuoted = table
      .getColumn(3)
      .isQuoted();
    String physicalNameCreated = table
      .getColumn(3)
      .getName();
    String implicitNameCreated = table
      .getColumn(2)
      .getName();

    SoftAssertions.assertSoftly(softly -> {
        softly
          .assertThat(columnNameIsQuoted)
          .isTrue();
        softly
          .assertThat(tableNameCreated)
          .isEqualTo(tableNameExpected);
        softly
          .assertThat(physicalNameCreated)
          .isEqualTo(physicalNameExpected);
        softly
          .assertThat(implicitNameCreated)
          .isEqualTo(implicitNameExpected);
    });
}
 
Example 6
@Test
public void givenDefaultBootNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
    String entity = Account.class.getCanonicalName();
    PersistentClass persistentClass = metadata.getEntityBinding(entity);
    Table table = persistentClass.getTable();
    String physicalNameExpected = "secondary_email";
    String implicitNameExpected = "default_email";
    String tableNameExpected = "account";

    String tableNameCreated = table.getName();
    String physicalNameCreated = table
      .getColumn(3)
      .getName();
    String implicitNameCreated = table
      .getColumn(2)
      .getName();

    SoftAssertions softly = new SoftAssertions();
    softly
      .assertThat(tableNameCreated)
      .isEqualTo(tableNameExpected);
    softly
      .assertThat(physicalNameCreated)
      .isEqualTo(physicalNameExpected);
    softly
      .assertThat(implicitNameCreated)
      .isEqualTo(implicitNameExpected);
    softly.assertAll();
}
 
Example 7
@Test
public void givenLegacyHbmImplNamingNamingStrategy_whenCreateDatabase_thenGetStrategyNames() {
    Metadata metadata = MetadataExtractorIntegrator.INSTANCE.getMetadata();
    String entity = Preference.class.getCanonicalName();
    PersistentClass persistentClass = metadata.getEntityBinding(entity);
    Collection<Table> tables = metadata
      .getDatabase()
      .getDefaultNamespace()
      .getTables();
    Table preferenceTable = persistentClass.getTable();
    String tableNameExpected = "Account_preferences";
    Table accountPreferencesTable = tables
      .stream()
      .filter(table -> table
        .getName()
        .equals(tableNameExpected))
      .findFirst()
      .get();
    String implicitNameExpected = "account";

    String implicitNameCreated = preferenceTable
      .getColumn(3)
      .getName();
    String tableNameCreated = accountPreferencesTable.getName();

    SoftAssertions.assertSoftly(softly -> {
        softly
          .assertThat(implicitNameCreated)
          .isEqualTo(implicitNameExpected);
        softly
          .assertThat(tableNameCreated)
          .isEqualTo(tableNameExpected);
    });
}
 
Example 8
/** 读取索引配置 */
private void readIndex(PersistentClass pclazz, Class<?> iface) {
	Table table = iface.getAnnotation(Table.class);
	if (table == null) {
		return;
	}
	org.hibernate.mapping.Table tb = pclazz.getTable();
	outloop: for (Index index : table.indexes()) {
		List<Identifier> columnNames = new ArrayList<>();
		org.hibernate.mapping.Index idx = new org.hibernate.mapping.Index();
		// columnList="fdId, fdName"
		String[] columns = index.columnList().split(",");
		for (String column : columns) {
			column = column.trim();
			int i = column.indexOf(' ');
			String order = null;
			if (i > -1) {
				order = column.substring(i).trim();
				column = column.substring(0, i);
			}
			Property property = pclazz.getProperty(column);
			org.hibernate.mapping.Column col = (org.hibernate.mapping.Column) property
					.getColumnIterator().next();
			if (col == null) {
				log.error(StringHelper.join(iface.getName(), "指定的索引列不存在:",
						column));
				continue outloop;
			}
			columnNames.add(Identifier.toIdentifier(column));
			idx.addColumn(col, order);
		}
		idx.setTable(tb);
		// 创建索引名称
		String name = index.name();
		if (StringUtils.isBlank(name)) {
			name = NamingHelper.INSTANCE.generateHashedConstraintName("IDX",
					idx.getTable().getNameIdentifier(), columnNames);
		}
		idx.setName(name);
		// 判断索引是否存在
		if (tb.getIndex(name) == null) {
			tb.addIndex(idx);
		}
	}
}
 
Example 9
public static int checkReferencedColumnsType(
		Ejb3JoinColumn[] columns,
		PersistentClass referencedEntity,
		MetadataBuildingContext context) {
	//convenient container to find whether a column is an id one or not
	Set<Column> idColumns = new HashSet<Column>();
	Iterator idColumnsIt = referencedEntity.getKey().getColumnIterator();
	while ( idColumnsIt.hasNext() ) {
		idColumns.add( (Column) idColumnsIt.next() );
	}

	boolean isFkReferencedColumnName = false;
	boolean noReferencedColumn = true;
	//build the list of potential tables
	if ( columns.length == 0 ) return NO_REFERENCE; //shortcut
	Object columnOwner = BinderHelper.findColumnOwner(
			referencedEntity,
			columns[0].getReferencedColumn(),
			context
	);
	if ( columnOwner == null ) {
		try {
			throw new MappingException(
					"Unable to find column with logical name: "
							+ columns[0].getReferencedColumn() + " in " + referencedEntity.getTable() + " and its related "
							+ "supertables and secondary tables"
			);
		}
		catch (MappingException e) {
			throw new RecoverableException( e.getMessage(), e );
		}
	}
	Table matchingTable = columnOwner instanceof PersistentClass ?
			( (PersistentClass) columnOwner ).getTable() :
			( (Join) columnOwner ).getTable();
	//check each referenced column
	for (Ejb3JoinColumn ejb3Column : columns) {
		String logicalReferencedColumnName = ejb3Column.getReferencedColumn();
		if ( StringHelper.isNotEmpty( logicalReferencedColumnName ) ) {
			String referencedColumnName;
			try {
				referencedColumnName = context.getMetadataCollector().getPhysicalColumnName(
						matchingTable,
						logicalReferencedColumnName
				);
			}
			catch (MappingException me) {
				//rewrite the exception
				throw new MappingException(
						"Unable to find column with logical name: "
								+ logicalReferencedColumnName + " in " + matchingTable.getName()
				);
			}
			noReferencedColumn = false;
			Column refCol = new Column( referencedColumnName );
			boolean contains = idColumns.contains( refCol );
			if ( !contains ) {
				isFkReferencedColumnName = true;
				break; //we know the state
			}
		}
	}
	if ( isFkReferencedColumnName ) {
		return NON_PK_REFERENCE;
	}
	else if ( noReferencedColumn ) {
		return NO_REFERENCE;
	}
	else if ( idColumns.size() != columns.length ) {
		//reference use PK but is a subset or a superset
		return NON_PK_REFERENCE;
	}
	else {
		return PK_REFERENCE;
	}
}