sqlplayframework-2.1ebean

Is it possible to cast a SqlQuery results from Ebean to a Model (Bean)?


Using Ebean (via Play Framework 2.1.1), I have to build a home made SQL query, but I'd like it to return directly a List<MyModel>, instead of a List<SqlRow> that I would have to query the database for each id from the result to have a List<MyModel>.

Is it possible to cast directly a SqlQuery/SqlRow to a Model ?

Actually, I do that :

SqlQuery query = Ebean.createSqlQuery("SELECT id FROM MyModel WHERE ...");
List<SqlRow> rows = query.findList(); // not directly possible.
List<MyModel> results = new ArrayList<MyModel>();
for (SqlRow row : rows) {
    results.add(MyModel.find.idEq(row.getLong("id)));
}

Ideally, it would be something like :

SqlQuery query = Ebean.createSqlQuery("SELECT id FROM MyModel WHERE ...");
List<MyModel> results = (List<MyModel>) query.findList(); // not directly possible.

This is not very efficient.


Solution

  • Try this:

    RawSql rawSql = RawSqlBuilder.parse("SELECT id, value, ... FROM MyModel WHERE ...")
                      .columnMapping("id", "id")
                      .columnMapping("value", "value")
                      //...
                      .create();
    
    Query<MyModel> query = Ebean.find(MyModel.class);
    query.setRawSql(rawSql);
    List<MyModel> result = query.findList();
    

    Or using the finder:

    Finder<Long, MyModel> finder = new Finder<Long, MyModel>(Long.class, MyModel.class);
    
    List<MyModel> result = finder.where()
                                 .eq("name", "Barack Obama")
                                 //...
                                 .findList();