Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do select in list with Ebean createSqlQuery

I'm building a Play2 app with Ebean. I have created a service class with a method for getting venues by a list of ids:

public static List<Venue> getVenuesForIds(List<Long> list){          
    ArrayList<Venue> venues = new ArrayList<Venue>();
    String sql = "select c.id, c.name from Company c where in (:ids)";
    List<SqlRow> sqlRows =
                Ebean.createSqlQuery(sql).setParameter("ids", list).findList();        
    for(SqlRow row : sqlRows) {
        venues.add(new Venue(row.getLong("id"), row.getString("name")));
    }        
    return venues;
}

But I'm getting:

[PersistenceException: Query threw SQLException:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'in (201639091,201637666)' at line 1 Query was: select c.id, c.name from Company c where in (?,?) ] 

I have read through http://www.avaje.org/ebean/introquery.html but probably missed the correct syntax. I want to do this in raw sql. What have I missed?

like image 256
jakob Avatar asked Dec 10 '12 15:12

jakob


2 Answers

Your request does not seem correct.

What about :

 "select c.id, c.name from Company c where c.id in (:ids)";
like image 54
Arnaud Gourlay Avatar answered Sep 25 '22 17:09

Arnaud Gourlay


You don't need to perform such 'sophisticated' query, it will be good enough if you'll use common Finder<I,T> in your Venue model (once):

@Entity
@Table(name = "Company")
public class Venue extends Model {

    @Id
    public Long id;
    public String name;
    // other fields

    public static Finder<Long, Venue> find
            = new Finder<Long, Venue>(Long.class, Venue.class);
}

So then you can do the same task with... single line of code in your method:

 public static List<Venue> getVenuesForIds(List<Long> ids){          
     return Venue.find.select("id,name").where().idIn(ids).findList();
 }

or with similar expresion:

 public static List<Venue> getVenuesForIds(List<Long> ids){          
     return Venue.find.select("id,name").where().in("id",ids).findList();
 }
like image 45
biesior Avatar answered Sep 25 '22 17:09

biesior