Contact Us 1-800-596-4880

Query Java Objects

MQL allows you to easily filter, transform and join objects from within your Java code. This example will show you how to filter a List of User objects.

Let’s say your User data base has a List of users like this:

List<User> users = new ArrayList<User>();users.add(new User("Dan", "Diephouse", "MuleSoft", "Engineering"));users.add(new User("Joe", "Sales", "MuleSoft", "Sales"));

where your User object has fields along with getters and setters for the fields:

public class User {    private String firstName;    private String lastName;    private String company;    private String division;    ...}

And you would like to filter these users to only include engineers.

First, populate the context:

Map<String,Object> context = new HashMap<String,Object>();context.put("users", users);

Then, execute your query to select them:

Collection<User> result =     Query.execute("from users where division = 'Engineering'", context);

You’ll get a single object back in the collection with the user "Dan Diephouse."

Transformation

Now, let’s say, you want to create an object with a name field which combines firstName and lastName. You can create a new Map of properties by doing this:

Collection<Map> result =     Query.execute("from users select new { name = firstName + ' ' + lastName }", context);

Each Map in the collection will have a single "name" key with the firstName concatenated to the lastName.