| Author |
Dynamically build a javaBean
|
David Wei
Greenhorn
Joined: Jan 04, 2002
Posts: 17
|
|
Is there a way to build a JavaBean dynamically based on the DB table column names and assoicated data? For example, if I get back of 5 columns in a db table, I need to create a javaBean with those 5 column names as variables and their getters/setters as well. Next time, if I get 7 columns, I can create a javaBean with 7 variables. Thanks in advance. David
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24045
|
|
|
The magic you're asking about is called "Object-Relational Mapping." We've got a whole forum devoted to this topic here. There are many tools -- commercial as well as free -- that do this for you. Perhaps the most popular Java ORM tool is Hibernate.
|
[Jess in Action][AskingGoodQuestions]
|
 |
jiju ka
Ranch Hand
Joined: Oct 12, 2004
Posts: 302
|
|
Is there a way to build a JavaBean dynamically based on the DB table column names and assoicated data? For example, if I get back of 5 columns in a db table, I need to create a javaBean with those 5 column names as variables and their getters/setters as well. Next time, if I get 7 columns, I can create a javaBean with 7 variables.
You may use reflection to accomplish this. It is going to be messy because to use the so created java beans the programmer don't have a pre-knowledge of various setters and getters. If you are not keen about the getters and setters, you may do the following. Keep the properties in a map (key value pair) where key is the field name/variable name/column name Value is the value of the field Define getValue(String fieldName) setValue(String fieldName, Object value) value could be of the type String or primitive wrappers. One advantage is that if you get the keys of the properties, you can know various fieldnames. This kind of beans is difficult to maintain especially debugging is tough. From my experience I like the proper getters and setters. If the structure of your table is not changing dynamically, you can assume the name of the accessors before using the beans.
|
 |
 |
|
|
subject: Dynamically build a javaBean
|
|
|