简体   繁体   中英

generic controller - play framework

I´ll show you the code. It will say more than words.

BaseModel:

import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Model;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@MappedSuperclass
public abstract class BaseModel extends Model {
@Id
public Long id;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public static <T extends Model> ExpressionList<T> find() {
    return null;
}
}

BaseController:

import com.avaje.ebean.ExpressionList;
import models.BaseModel;
import play.db.ebean.Model;
import play.libs.Json;
import play.mvc.Controller;

import javax.xml.transform.Result;

public class BaseController<T extends BaseModel> extends Controller {

private Model.Finder<Long,T> finder;

public  Result GetAll() {


    List<T> list = T.find().where().orderBy("name asc").findList();

    if (request().accepts("text/html")) {
        return ok(index.render(list));
    } else{
        return badRequest();
    }


    if (request().accepts("application/json")) {
        return ok(Json.toJson(list));
    } else {
        return badRequest();
    }
}

I have a problem with the list

 List<T> data = T.find().where().orderBy("buildingTypeId asc").findList();

Required List <T>
Found List<com.avaje.ebean.Model>

The problem is in the code List<T> list = T.find().where().orderBy("name asc").findList(); the findList() method can not return the List<T> because it doesn't know the corresponding type of T . Only the BaseController class knows it.

I tried this: List<T> list = finder.where().orderBy("name asc").findList(); and it works, maybe it is what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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