Java – how to find fully qualified table columns from hibernate metadatasources

I have an entity, and I have a class < myentity > reference:

@Entity
class MyEntity {
    @Id int id;
    @Column String col1;
    @Column(name = "abc") String col2;
}

I am currently using hibernate to export my entity to the in memory database, as shown below:

MetadataSources Metadata = new MetadataSources(...);
Metadata.addAnnotatedClass(MyEntity.class);
SchemaExport export = new SchemaExport();
export.create(EnumSet.of(TargetType.DATABASE),Metadata.buildMetadata());

Details about the Hibernate-specific API here.

Is there a reliable way to get from myentity.com through hibernate API Col2 (annotated Java field reference) to the fully qualified column name in the database (and vice versa)? Without explicit qualification, I want to avoid re implementing all the details of how Java identifiers (including getters and setters) map to SQL identifiers

Solution

This is a very good question, so I decided to use an article to answer it in more detail

org. hibernate. boot. Metadata is of interest to us because it contains persistentclass entity binding

First, you need to create an integrator to access the metadata:

public class MetadataExtractorIntegrator 
    implements org.hibernate.integrator.spi.Integrator {

    public static final MetadataExtractorIntegrator INSTANCE = 
        new MetadataExtractorIntegrator();

    private Database database;

    private Metadata Metadata;

    public Database getDatabase() {
        return database;
    }

    public Metadata getMetadata() {
        return Metadata;
    }

    @Override
    public void integrate(
            Metadata Metadata,SessionFactoryImplementor sessionFactory,SessionFactoryServiceRegistry serviceRegistry) {

        this.database = Metadata.getDatabase();
        this.Metadata = Metadata;

    }

    @Override
    public void disintegrate(
        SessionFactoryImplementor sessionFactory,SessionFactoryServiceRegistry serviceRegistry) {

    }
}

If you use JPA, you can register as follows:

Map<String,Object> configuration = new HashMap<>();

Integrator integrator = integrator();
if (integrator != null) {
    configuration.put("hibernate.integrator_provider",(IntegratorProvider) () -> Collections.singletonList(
            MetadataExtractorIntegrator.INSTANCE
        )
    );
}

EntityManagerFactory entityManagerFactory = new EntityManagerFactoryBuilderImpl(
    new PersistenceUnitInfoDescriptor(persistenceUnitInfo),configuration
)
.build();

Now, when running the following test cases:

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()
            );
        }
    }
}

Against the following entities:

We get the following output:

Entity: com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider$Tag is mapped to table: tag
Property: name is mapped on table column: name of type: varchar(255)
Property: version is mapped on table column: version of type: integer

Entity: com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider$PostComment is mapped to table: post_comment
Property: post is mapped on table column: post_id of type: bigint
Property: review is mapped on table column: review of type: varchar(255)
Property: version is mapped on table column: version of type: integer

Entity: com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider$Post is mapped to table: post
Property: title is mapped on table column: title of type: varchar(255)
Property: version is mapped on table column: version of type: integer

Entity: com.vladmihalcea.book.hpjp.util.providers.entity.BlogEntityProvider$PostDetails is mapped to table: post_details
Property: createdBy is mapped on table column: created_by of type: varchar(255)
Property: createdOn is mapped on table column: created_on of type: datetime(6)
Property: version is mapped on table column: version of type: integer

It's cool, isn't it?

You can also view this example on GitHub

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>