Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

hibernate - Dynamically create table and Java classes at runtime

I have a requirement in my application. My tables won't be defined beforehand.

For example, if a 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 etc. And also its related class and its Hibernate mapping file.

Is there any way of doing so?

Thanks in advance,
Rima Desai

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...