• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dynamically build a javaBean

 
David Wei
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
jiju ka
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic