开发者

Encapsulating generic database methods in a Java superclass and then calling from Child classes doesn't work without a cast. HELP

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜