2014-09-19 76 views
3

原始SQL時,使用由Ebean創建Postgres的表,我想查詢這些表用手寫聲明結果:如何映射查詢使用Ebean

SELECT r.name, 
     r.value, 
     p.name as param1, 
     a.name as att1, 
     p2.name as param2, 
     a2.name as att2 
FROM compatibility c 
JOIN attribute a ON c.att1_id = a.id 
JOIN attribute a2 ON c.att2_id = a2.id 
JOIN PARAMETER p ON a.parameter_id = p.id 
JOIN PARAMETER p2 ON a2.parameter_id = p2.id 
JOIN rating r ON c.rating_id = r.id 
WHERE p.problem_id = %d 
    OR p2.problem_id = %d 

每個連接表的代表之一我模型類。 該查詢執行得很好,但我不知道如何繼續:

我該如何使用Play 2.2執行查詢。和Ebean? 如何將此查詢映射到可迭代對象?我是否需要創建一個包含查詢中所有字段的Model類,或者我可以使用某種類型的HashMap? 如何以安全的方式參數化查詢?

回答

6

要執行此查詢,您需要使用RawSql類。您還必須創建要將結果輸出到的課程。

下面是示例性結果類的代碼:

import javax.persistence.Entity;  
import com.avaje.ebean.annotation.Sql; 

@Entity 
@Sql 
public class Result { 

    String name; 
    Integer value; 
    String param1; 
    String param2; 
    String att1; 
    String att2; 
} 

而且例如執行這個查詢的:

String sql 
    = " SELECT r.name," 
    + " r.value," 
    + " p.name as param1," 
    + " a.name as att1," 
    + " p2.name as param2," 
    + " a2.name as att2" 
    + " FROM compatibility c" 
    + " JOIN attribute a ON c.att1_id = a.id" 
    + " JOIN attribute a2 ON c.att2_id = a2.id" 
    + " JOIN PARAMETER p ON a.parameter_id = p.id" 
    + " JOIN PARAMETER p2 ON a2.parameter_id = p2.id" 
    + " JOIN rating r ON c.rating_id = r.id" 
    + " WHERE p.problem_id = %d" 
    + " OR p2.problem_id = %d" 

RawSql rawSql = 
    RawSqlBuilder 
     .parse(sql) 
     .columnMapping("r.name", "name") 
     .columnMapping("r.value", "value") 
     .create(); 

Query<Result> query = Ebean.find(Result.class); 
query.setRawSql(rawSql) 
    .where().gt("amount", 10);  

List<Result> list = query.findList();