Display RawSql result for an object in Java Ebean

Say I have an Article class that automatically displays Java Ebean as a database table.

For this table, I wanted to get records through a RawSql query, because I find SQL simpler when it receives complex queries with many joins, etc. At the moment, I managed to pass the SQL statement to Parser. The request is correct, I already checked this.

The only problem is that I don’t know how to match the database results with my Article class. I know that there is a columnMapping(...) method, but to be honest, I have to be lazy to map each individual column manually ...

Is there no other way, just like myResults.mapToClass(Article.class) to extract something like List<Article> ?

This is the code that I already have:

 Finder<String, Article> find = new Finder<String, Article>( String.class, Article.class); String sql = "SELECT * FROM article [...]"; RawSql rawSql = RawSqlBuilder.parse(sql).create(); List<Article> returnList = find.setRawSql(rawSql).findList(); 

As an alternative:

 Finder<String, Article> find = new Finder<String, Article>( String.class, Article.class); String sql = "SELECT id, title, sub_title FROM article [...]"; RawSql rawSql = RawSqlBuilder.parse(sql) .columnMapping("id", "id") .columnMapping("title", "title") .columnMapping("sub_title", "subTitle") .create(); List<Article> resultList = find.setRawSql(rawSql).findList(); 
+4
source share
1 answer

Since the question was asked, a lot of events have happened in Ebean, but I think the problem remains valid. the new RawSqlBuilder.tableMapping () makes things easier, as shown in the code below, but afaik still needs to manually map all attributes (no SELECT table.* FROM table )

I have this exact problem, and I worked on it by creating a helper object (@ Entity / @ Sql) that I map to. For instance. CustomerWithPurchaseStats .

Extract:

 @Entity @Sql public class CustomerWithPurchaseStats { @OneToOne private Customer customer; ... 

And in the DAO :

 public List<CustomerWithPurchaseStats> getAllCustomersWithPurchaseStats() { StringBuilder sql = new StringBuilder("SELECT cu.id, <manually add all fields you need mapped ").append(" FROM customer cu "); RawSqlBuilder rawSqlBuilder = RawSqlBuilder.parse(sql.toString()); rawSqlBuilder.tableAliasMapping("cu", "customer").create(); return Ebean.find(CustomerWithPurchaseStats.class) .setRawSql(rawSqlBuilder.create()) .findList(); } 
0
source

Source: https://habr.com/ru/post/1486822/


All Articles