简体   繁体   English

Play的通用包装方法! 楷模

[英]Generic wrapper method for Play! models

I'm trying to implement a RESTful interface for my Play! 我正在尝试为我的Play实现RESTful接口! framework models using a generic wrapper. 使用通用包装的框架模型。

I want to use a generic method to call and return each model's respective "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: 在我的控制器的GET方法中,根据通过特定路由请求的模型,上述方法被称为如下:

getModel(new User(), params);

Since the find() methods are actually static methods of the GenericModels class, it should entirely be possible. 由于find()方法实际上是GenericModels类的静态方法,因此应该完全有可能。 However, since Play generates the code for each defined model I get this error: 但是,由于Play为每个定义的模型生成代码,因此出现此错误:

UnsupportedOperationException occured : Please annotate your JPA model with @javax.persistence.Entity annotation. 发生UnsupportedOperationException:请使用@ javax.persistence.Entity批注对您的JPA模型进行批注。

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? 我是否必须为每个类繁琐地实现相同的GET,PUT,UPDATE,DELETE方法?

I think "model.findById" calls the GenericModel.findById static function which is not implemented and generates the exception. 我认为“ model.findById”调用了GenericModel.findById静态函数,该函数未实现并生成异常。 It doesn't call the static function enhanced by JPAPlugin at runtime. 它不会在运行时调用JPAPlugin增强的静态函数。

I'm not sure it will work but you should try to call directly JPQL function, something like: 我不确定它是否可以工作,但是您应该尝试直接调用JPQL函数,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM