Reputation: 1728
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
Upvotes: 2
Views: 7342
Reputation: 90427
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)
Upvotes: 2
Reputation: 46
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.
Upvotes: 0
Reputation: 5273
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.
Upvotes: 0