views:

147

answers:

4

Getting data from a database table to an object in code has always seemed like mundane code. There are two ways I have found to do it: 1) have a code generator that reads a database table and creates the class and controller to map the datafields to the class fields or 2) use reflection to take the database field and find it on the class.

1 seems to me like I'm missing something because I have to create a controller for every table.

2 seems to be too labor intensive once you get into heavy data access code.

Is there a third route that I should try to get data from a database onto my objects?

A: 

I use reflection to map data back and forth and it works well even under heavy data access. The "third route" is to do everything by hand, which may be faster to run but really slow to write.

Otávio Décio
+3  A: 

You normally use OR (Object-Relational) mappers in such situations. A good framework providing OR functionality is Hibernate. Does this answer your question?

lewap
A: 

I agree with lewap, an ORM (object-relational mapper) really helps in these situations. You may also want to consider the Active Record pattern (discussed in Fowler's Patterns of Enterprise Architecture book). It can really speed up creation of the DAL in simple apps.

Nebakanezer
+1  A: 

I think the answer to this depends on the available technologies for the language you are going to use.

I for one am very successful with the use of an ORM (NHibernate) so naturally I may recommend option one.

There are other options that you may wish to take though:

  • If you are using .NET, you may opt to use attributes for your class properties to serve either as a mapping within a class, or as data that can be reflected
  • If you are using .NET, Fluent NHibernate will make it quite easy to make type-safe mappings within your code.
  • You can use generics so that you will not need to make a controller for every table, although I admit that it will be likely that you will do the latter anyway. However the generics can contain most of the general CRUD methods that is common to all tables, and you will only need to code specific quirks.
Jon Limjap