Generic wrapper method for Play! models
I'm trying to implement a RESTful interface for my Play! framework models using a generic wrapper.
I want to use a generic method to call and return each model's respective 开发者_JS百科"find" methods.
private static <T extends GenericModel> void getModel(T model, Params params){
if (params._contains("id")){
renderJSON(model.findById(params.get("id", Long.class)));
}
else{
renderJSON(model.findAll());
}
}
The above method is called as follows, in my controller's GET method according to which model is requested through a particular route:
getModel(new User(), params);
Since the find() methods are actually static methods of the GenericModels class, it should entirely be possible. However, since Play generates the code for each defined model I get this error:
UnsupportedOperationException occured : Please annotate your JPA model with @javax.persistence.Entity annotation.
At least, I think that's why. Is there no way around this? Am I forced to tediously implement the same GET, PUT, UPDATE, DELETE methods for each class?
I think "model.findById" calls the GenericModel.findById static function which is not implemented and generates the exception. It doesn't call the static function enhanced by JPAPlugin at runtime.
I'm not sure it will work but you should try to call directly JPQL function, something like:
private static <T extends GenericModel> void getModel(Class<T> clazz, Params params){
if (params._contains("id")){
renderJSON(JPQL.instance.findById(clazz.getSimpleName(), params.get("id", Long.class)));
}
else{
renderJSON(model.findAll());
}
and call it like the following:
getModel(new User(), User.class, params);
精彩评论