简体   繁体   English

如何使用JDBC / Hibernate基于用户输入数据生成“创建表”查询?

[英]How can I generate a 'create table' query based on user input data using JDBC/Hibernate?

Assume if we are giving the query data in a csv file as such below: 假设我们是否在csv文件中提供查询数据,如下所示:

Emp_Id, Emp_Name, Address

Now, the query (Mysql) like below should be generated and processed. 现在,应生成并处理以下查询(Mysql)。

Create TABLE Emp_tbl(
   Emp_id INT NOT NULL,
   Emp_Name VARCHAR(100) NOT NULL,
   Address VARCHAR(400) NOT NULL,
   PRIMARY KEY ( Emp_id )
);

Thanks in Advance!! 提前致谢!!

You can achieve it by jdbc: 您可以通过jdbc实现它:

String sql_stmt = "Create TABLE Emp_tbl(
   Emp_id INT NOT NULL,
   Emp_Name VARCHAR(100) NOT NULL,
   Address VARCHAR(400) NOT NULL,
   PRIMARY KEY ( Emp_id )
);";

public void createTable(String sql_stmt) throws SQLException {

    // your connection code
    statement = connection.createStatement();

    statement.executeUpdate(sql_stmt);
}

Also here is about map dynamically created table in hibernate : 也是关于在休眠状态下动态创建表的映射:

It can be done dynamically, but it's somewhat messy: 它可以动态完成,但有些混乱:

You'll need to dynamically alter Hibernate's Configuration object before SessionFactory is built. 在建立SessionFactory之前,您需要动态更改Hibernate的Configuration对象。 If you're using Spring, this can be done by overriding postProcessAnnotationConfiguration() method of AnnotationSessionFactoryBean; 如果您使用的是Spring,则可以通过重写AnnotationSessionFactoryBean的postProcessAnnotationConfiguration()方法来实现。 otherwise you'll just need to do it using your Configuration object prior to invoking buildSessionFactory() on it. 否则,在调用buildSessionFactory()之前,您只需要使用Configuration对象即可完成此操作。

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). 如果您需要在不重新启动应用程序的情况下执行此操作,则可以查看重建SessionFactory(这意味着您的用户将不得不等到完成此操作),或者使用专门用于自定义类的单独SessionFactory实例(这几乎是不可能的)如果您的自定义类需要引用您的内置类)。

You can get access to class / table mappings via configuration.getMappings(). 您可以通过configuration.getMappings()访问类/表映射。 You will then need to create a new table mapping via Table API and add it to configuration via addTable(). 然后,您将需要通过Table API创建一个新的表映射,并通过addTable()将其添加到配置中。 Same thing will have to be done with PersistentClass which represents a class mapping. 代表类映射的PersistentClass必须做同样的事情。 If you're using the same class to represent multiple entities (eg 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. 每次重新启动应用程序时,都必须执行此操作(更改配置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM