Hibernate upgrade to 5.2 - Session Factory creation and replacing PersistentClass for getting entity class properties

不打扰是莪最后的温柔 提交于 2019-11-29 13:33:28

Great question. In fact, I liked it so much that I wrote an article about it.

First, we need to create a new Integrator:

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

    public static final MetadataExtractorIntegrator INSTANCE = 
        new MetadataExtractorIntegrator();

    private Database database;

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

        database = metadata.getDatabase();
    }

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

    }

    public Database getDatabase() {
        return database;
    }
}

Then, we can just configure Hibernate to use it.

If you're using the Hibernate bootstrap mechanism, then you can add it like this:

final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder();
bsrb.enableAutoClose();

Integrator integrator = integrator();
if (integrator != null) {
    bsrb.applyIntegrator( integrator );
}

final BootstrapServiceRegistry bsr = bsrb.build();

final StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder(bsr);

If you're bootstrapping with JPA, then you can do it as follows:

protected EntityManagerFactory newEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(
        getClass().getSimpleName()
    );

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


    configuration.put("hibernate.integrator_provider", 
        (IntegratorProvider) () -> Collections.singletonList( MetadataExtractorIntegrator.INSTANCE )
    );

    EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = new EntityManagerFactoryBuilderImpl(
            new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration
    );
    return entityManagerFactoryBuilder.build();
}

Now, when running the following test:

for(Namespace namespace : MetadataExtractorIntegrator.INSTANCE
    .getDatabase()
    .getNamespaces()) {

    for( Table table : namespace.getTables()) {
        LOGGER.info( "Table {} has the following columns: {}",
             table,
             StreamSupport.stream(
                Spliterators.spliteratorUnknownSize( 
                    table.getColumnIterator(), 
                    Spliterator.ORDERED
                ), 
                false
            )
            .collect( Collectors.toList()) 
        );
    }
}

Hibernate outputs all the currently mapped tables in the log:

Table org.hibernate.mapping.Table(post) has the following columns: [
    org.hibernate.mapping.Column(id), 
    org.hibernate.mapping.Column(title), 
    org.hibernate.mapping.Column(version)
]
Table org.hibernate.mapping.Table(post_comment) has the following columns: [
    org.hibernate.mapping.Column(id), 
    org.hibernate.mapping.Column(review), 
    org.hibernate.mapping.Column(version), 
    org.hibernate.mapping.Column(post_id)
]
Table org.hibernate.mapping.Table(post_details) has the following columns: [
    org.hibernate.mapping.Column(id), 
    org.hibernate.mapping.Column(created_by), 
    org.hibernate.mapping.Column(created_on), 
    org.hibernate.mapping.Column(version)
]
Table org.hibernate.mapping.Table(post_tag) has the following columns: [
    org.hibernate.mapping.Column(post_id), 
    org.hibernate.mapping.Column(tag_id)
]
Table org.hibernate.mapping.Table(tag) has the following columns: [
    org.hibernate.mapping.Column(id), 
    org.hibernate.mapping.Column(name), 
    org.hibernate.mapping.Column(version)
]

That's it!

Well finally I did it thank's to Vlad's article. I took the integrator code without any change and modified my HibernateUtil and the getColumns() method. So here's my code:

SessionFactory creation:

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    public static SessionFactory getSessionFactory() {
        return buildSessionFactory();
    }

    private static SessionFactory buildSessionFactory() {
        final BootstrapServiceRegistry bootstrapServiceRegistry = new BootstrapServiceRegistryBuilder().enableAutoClose()
                .applyIntegrator(MetadataExtractorIntegrator.INSTANCE).build();

        final StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder(bootstrapServiceRegistry).configure().build();
        return new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
    }

    public static Session getSession() {
        Session hibernateSession = getSessionFactory().getCurrentSession();
        return hibernateSession;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Metadata Extractor(Get Column names):

public static List<String> getColumnNames(String tableName) {

    List<String> columnList = new ArrayList<>();

    for (Namespace namespace : MetadataExtractorIntegrator.INSTANCE.getDatabase().getNamespaces()) {
        for (Table table : namespace.getTables()) {
            if (table.getName().equalsIgnoreCase(lookupTableName)) {
                Iterator<Column> iterator = table.getColumnIterator();
                while (iterator.hasNext()) {
                    columnList.add(iterator.next().getName());
                }
                break;
            }
        }
        if (!columnList.isEmpty())
            break;
    }
    return columnList;
}

An easier way to get column name with hibernate 5

final AbstractEntityPersister classMetadata = (AbstractEntityPersister) sessionFactory.getClassMetadata(clazz)
final String[] names = classMetadata.getPropertyColumnNames(property)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!