Now, we have retrieved an object by its id. Now, let's complete the example obtaining collections. First of all, we'll complete the configuration to adapt our ORM to our database and entities (remember, all this code is in the source code's tests):
@Override
protected void configureOrm(final OrmConfiguration ormConfig) {
ormConfig
.idAttributeIs("id")
.entity(Issue.class)
.mapsToTable("issues")
.mapsAttribute("issueId").with("id")
.entity(User.class)
.mapsAttribute("id").with("userId");
}
Now, for the collections. Easy, just:
// Retrieve a map of users, using each primary key as key and a filter
final Map<Object, User> mapOfUsers = new IssuesDb().orm()
.loadMap(User.class, new Filter("userId>?", new Object[] { 1 }));
final User userWithId2 = mapOfUsers.get(2);
// Retrieve a list of users, a filter and a query modifier
final List<User> listOfUsers = new IssuesDb().orm().loadList(
User.class, new Filter("userId>?", new Object[] { 1 }),
"order by name desc");
final User user = listOfUsers.get(0);
// Retrieve a list of users, a filter and a query modifier
final List<User> users = new IssuesDb().orm()
.getList(User.class, new Filter("userId>?", new Object[] { 1 }),
"order by name desc");
final User user = users.get(0);
// Retrieve a list of users using a Select
final List<User> listOfUsersUsingSelect = new IssuesDbExamples().orm()
.loadList(User.class,
new Select<Object>("Select user with userId 1",
"select name from user where userId>? order by name",
new Object[] { 1 }, null));
// Here the ResultHandler is not used
final User user = listOfUsersUsingSelect .get(0);
Nothing to comment here except for the last case: fetching objects using a Select. Keep in mind how MILK maps (if it finds attribute it will set the value, if not it will ignore it): this feature allows you to retrieve certain fields of an object, ignoring other. In this case, for example, the list of users will only contain their names.
Now. We've retrieved objects but, how do we create them? Ok, ok, smarty-pants, let's go to the saving objects section.