Search code examples
playframeworkebean

Ebean Select only particular Column


i have a class product with fields id , name , price etc,...

i want to fetch only name from the table ..

Am currently using this query

 String sql =   "select name from product where price = 100";
 SqlQuery sqlQuery = Ebean.createSqlQuery(sql);
  List<SqlRow> list = sqlQuery.findList();

what is the alerternate way to find using List but fetch only name

List<product> list = product.find.where("price = 100").select("name").findList();

i dont think the following query is efficient since it fetches all data and returns wat we filter it

  List<String> list = new ArrayList<String>();

    for(product p: product.find.select("name").findList())
     {
        list.add(p.name);
    }


return list;

Solution

  • By default .select("name") automatically includes the Id column. So in SQL you will see select t0.id, t0.name from ...

    If you add setDistinct(true) to the query, then that tells Ebean to not include the Id column and you will see in SQL select distinct t0.name from ...

    Try

    product.find .where().eq("price", 100) .setDistinct(true).select("name") .findList();