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
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