如何在Hibernate中动态创建表格? [英] How to map dynamically created table in Hibernate?

查看:233
本文介绍了如何在Hibernate中动态创建表格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Web应用程序。我们在项目中使用Hibernate作为ORM。实际上,我们的应用程序会根据用户选择动态地创建一些表格。用户可以选择表名,列名,然后他/她可以从csv文件导入数据。所以我的问题是:如何将这个动态创建的表与Hibernate和Java对象进行映射?解析方案

它可以动态完成,但它有点麻烦:



在构建SessionFactory之前,您需要动态更改Hibernate的Configuration对象。如果您使用的是Spring,可以通过覆盖 AnnotationSessionFactoryBean postProcessAnnotationConfiguration()方法来完成。否则你只需要在调用 buildSessionFactory()之前使用Configuration对象来完成它。



如果您需要在不重新启动应用程序的情况下执行此操作,那么您需要重新构建SessionFactory(这意味着您的用户将不得不等待,直到完成)或使用专门用于您的自定义类的单独SessionFactory实例(这是几乎不可能的如果您的自定义类需要引用您的内置类)。

您可以通过 configuration.getMappings()获得类/ 。然后,您需要通过 Table API创建新的表格映射,并通过 addTable()将其添加到配置中。 PersistentClass 也必须完成同样的事情它代表一个类映射。如果您使用相同的类来表示多个实体(例如,映射多个表),请确保为每个实体使用唯一的实体名称。您必须在每次重新启动应用程序时执行此操作(更改配置)。

I am working on a web application. We are using Hibernate as ORM in our project. Actually, our application creates some tables dynamically based on user selection. The user can select table name, column name and then s/he can import data from a csv file. So my question is: how to map this dynamically created table with Hibernate and Java objects?

解决方案

It can be done dynamically, but it's somewhat messy:

You'll need to dynamically alter Hibernate's Configuration object before SessionFactory is built. If you're using Spring, this can be done by overriding postProcessAnnotationConfiguration() method of AnnotationSessionFactoryBean; otherwise you'll just need to do it using your Configuration object prior to invoking buildSessionFactory() on it.

If you need to do this without application restart, you're looking at either rebuilding your SessionFactory (which means your users will have to wait until that's done) or using a separate SessionFactory instance specifically dedicated to your custom classes (which is next to impossible if your custom classes need to reference your built-in classes).

You can get access to class / table mappings via configuration.getMappings(). You will then need to create a new table mapping via Table API and add it to configuration via addTable(). Same thing will have to be done with PersistentClass which represents a class mapping. If you're using the same class to represent multiple entities (e.g. map multiple tables) make sure to use unique entity names for each. You'll have to do this (alter the configuration) on every app restart.

这篇关于如何在Hibernate中动态创建表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆