Dynamically create table and java classes at runtime

rima picture rima · Jul 28, 2009 · Viewed 19.2k times · Source

I have a requirement in my application. My tables wont be defined beforehand.For Example,if the user creates a form by name Student,and adds its attributes like name,roll no,subject,class etc.. then on runtime,there should be a table created by name student with columns name,roll no,subject,class and also its related class and its hibernate mapping file. Is there any way of doing so?

Thanks in advance,

Rima Desai

Answer

Gregory Mostizky picture Gregory Mostizky · Jul 28, 2009

It's possible, but it's not clear why would you want to do something like that, so it's hard to suggest any specific solution.

But generally, yes, you can generate database tables, hibernate classes and mappings dynamically based on some input. The easiest approach is to use some template engine. I've used Velocity in the past and it was very good for this task, but there are others too if you want to try them.

EDIT:

Following OP clarification the better approach is to use XML to store user defined data. The above solution is good but it requires recompiling the application whether forms are changed. If you don't want to stop and recompile after each user edit, XML is much better answer.

To give you some head start:

@Entity
public class UserDefinedFormData {
    @Id
    private long id;

    @ManyToOne
    private FormMetadata formMetadata;

    @Lob
    private String xmlUserData;
}

Given a definition of the form it would trivial to save and load data saved as XML.

Add a comment if you would like some more clarifications.