views:

20

answers:

2

I'm having a heap of trouble with Java coming from a PHP background. I've got a parent class Entity containing generic database methods, such as a static method getById(int id). My aim is to have children of this class, such as Person, so that I can call:

Person p = Person.getById(1);

At the moment this doesn't work, as getById(1) returns an Entity not a Person. I could cast the result, but there has to be a better way than doing a cast every time you call one of the generic methods?

In PHP, my last line would've been something like:

return new static(..);

As far as I can tell, I can't accomplish this in Java due to a lack of reified generics?

Any help would be appreciated. If this is something that isn't possible, I'd gladly accept suggestions as to a better approach

A: 

You want to follow the DAO pattern. Design an interface PersonDao with methods save, load, update, etc....provide an implementation. Persistence operations should go in DAOs, not on the domain classes -- those provide business logic (like giving the fullname of the Perso based on first and last, for example).

If you are really ambitious you can define a generic DAO and your implementations should be really simple, because all the functionality is defined generically. google around for that...

edit -- i did it for you

http://www.ibm.com/developerworks/java/library/j-genericdao.html

hvgotcodes
A: 

You would need to write a static method getById on the Person class which returns a Person. Can I assume here that you were planning, inside getById, to use reflection to set all of the member variables and require that they are the same as the columns in the database? Or do you plan to use a HashMap and store the column values there?

I would much prefer a solution where the object is well-defined with specific members and you can overwrite an abstract method in the Entity class to unpack the database record into the member variables. There would also have to be an abstract method to work the other way. This would basically require each class to define its own getById method for consistency. You wouldn't be able to enforce that through abstraction, but you could keep it as a standard.

Erick Robertson