2

I am new to hibernate and I need to create database table on fly. Which means I will be taking table details from User from UI. Lets say we restrict the user on number of table attributes(column) to 5 or so.

I've gone through various tutorials on hibernate and I see we can create a table but for that we need a class beforehand. But in my case everything is going to be dynamic.

As compared to JDBC, we can directly shoot a CREATE TABLE query and pass the table parameters into the query in java code.

My web application uses a REST web service, spring 3 framework and MySQL as database.

Any tutorial links or sample code would be really helpful

Thanks

3 Answers 3

2

I think you can make use of the SchemaExport class which has the method create() to generate table schema creation scripts from a set of given hibernate mapping files and then execute these scripts.

You should create the hibernate mapping XML pragmatically according to the information entered by user and feed this XML into the Configuration object that is passed to the SchemaExport object . Something likes this:

Configuration config = new Configuration();
// mappingClass.xml is generated according to the information entered by user
config.addResource("mappingClass.xml");  

SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true,true)  
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, is there a way I can atleast upload .csv or excel files via hibernate? By this i mean the table would get created on fly
I think it cannot because hibernate does not understand the format of your .csv or excel file . You have to convert them to a format that hibernate can understand , which is the hibernate mapping XML .
0

This is not the answer you want to hear, but I'm afraid hibernate can't create tables at runtime. As an alternative you could implement a key-value table, associate it with the user table and store attributes there. Thats how its usually done.

2 Comments

really! Then how I should achieve my task?
@Dhruv: Read my answer to the end.
0

Take a look at Apache CouchDB. It looks like good fit in your case. By adding new tables through code, you are inviting trouble. If this for a production environment solution, I would humbly ask you to reconsider. You don't want to be doing DBA stuff through code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.