Reputation: 667
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;
Upvotes: 2
Views: 4584
Reputation: 4021
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();
Upvotes: 3
Reputation: 4021
Ebean has findSingleAttributeList()
and findSingleAtrribute()
so the alternative answer would be:
List<String> productNames =
product.find
.where().eq("price", 100)
.select("name")
.findSingleAttributeList();
Upvotes: 7