Dynamic query in eBean

218 views
Skip to first unread message

Justin Lolofie

unread,
May 17, 2017, 3:22:45 PM5/17/17
to Ebean ORM

I have a small project with a model that has ~6 string properties and 1 date. I'm writing a search method. The user can supply any (or none) of those fields and I want to find matching objects.

Is it possible to build this query dynamically?

myQuery = myModel.find.where()

for (k, v in params) {
 myQuery.eq(k, v)
}

results = myQuery.execute()

Can I do this or do I have to build sql?


Daryl Stultz

unread,
May 17, 2017, 3:34:28 PM5/17/17
to eb...@googlegroups.com
On Wed, May 17, 2017 at 3:22 PM, Justin Lolofie <jta...@gmail.com> wrote:

I have a small project with a model that has ~6 string properties and 1 date. I'm writing a search method. The user can supply any (or none) of those fields and I want to find matching objects.

Is it possible to build this query dynamically?

Have you tried it? It's certainly possible to build dynamic queries, easier if you are using the "non-type safe" API. Can you describe an error you are getting, maybe show type declarations in the sample code?

/Daryl

Justin L.

unread,
May 17, 2017, 3:50:55 PM5/17/17
to eb...@googlegroups.com
No I havent found the equivalent of the "execute" in my psuedo code.
I'll keep looking.
> --
>
> ---
> You received this message because you are subscribed to a topic in the
> Google Groups "Ebean ORM" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/ebean/L_dWpu3eIIo/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> ebean+un...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Justin L.

unread,
May 17, 2017, 4:12:36 PM5/17/17
to eb...@googlegroups.com
For the next guy, this is what I came up with:

String ebeanQL = "find MyThing where";
Finder<Long, MyThing> finder = MyThing.find;
com.avaje.ebean.Query<MyThing> query = finder.setQuery(ebeanQL);

for {
query.setParameter(key, value);
}

List<MyThing> results = finder.findList();

Daryl Stultz

unread,
May 17, 2017, 4:19:51 PM5/17/17
to eb...@googlegroups.com
On Wed, May 17, 2017 at 4:12 PM, Justin L. <jta...@gmail.com> wrote:
For the next guy, this is what I came up with:

String ebeanQL = "find MyThing where";
Finder<Long, MyThing> finder = MyThing.find;
com.avaje.ebean.Query<MyThing> query = finder.setQuery(ebeanQL);

for {
    query.setParameter(key, value);
}

List<MyThing> results = finder.findList();



This could also be done with:

Query<MyThing> query = Ebean.find(MyThing.class)
for ... {
  query.where().eq(key, value);
}
List<MyThing> results = query.findList();

/Daryl
Reply all
Reply to author
Forward
0 new messages