Here is where the principle of Convention over Configuration enters. As long as our objects have attributes (with public getters and setters) with the same name as our tables, we'll be able to do this:
public class User {
private Integer id;
private String name;
private String surname;
private Integer age;
private Boolean active;
private transient Integer unimportantField;
.... Getters and setters ...
}
// We'll obtain now one (or zero) users
final Select<User> queryFindUserAsObject = new Select<User>(
"Find user", "select * from user where userId=?",
new Object[] { 1 }, Mappings.toObject(User.class));
final User user = new IssuesDb().sql().run(queryFindUserAsObject);
Assert.assertEquals(Integer.valueOf(1), user.getId());
One thing to note here is that we have a transient field (unimportantField). This field will not be obtained from the database. This is the way we have to ignore fields in the mapping.
Simple, isn't it? Now we retrieve rows and maps of users:
// We'll use this query as template (so we illustrate also how to clone a query)
final Select<DataList> queryAllUsers = new Select<DataList>(
"Select all users", "select * from user",
Mappings.toDataList());
// Obtaining a list of users...
final Select<List<User>> queryAllUsersAsObjects = new Select<List<User>>(
queryAllUsers, Mappings.toObjectList(User.class)); // We
// clone queryAllUsers, but change the mapping
final List<User> users = new IssuesDb().sql().run(
queryAllUsersAsObjects);
final User user = users.get(0); // User at index 0
// Obtaining a map of users using userId as key...
final Select<ObjectMap<User>> queryAllUsersAsMapOfObjects = new Select<ObjectMap<User>>(
queryAllUsers, Mappings.toObjectMap(User.class, "userId"));
final ObjectMap<User> usersMap = new IssuesDb().sql().run(
queryAllUsersAsMapOfObjects);
final User userWithId1 = users.get(1); // User with userId = 1
And that's it! Now for some updates...
Wiki: Examples
Wiki: Launch_queries
Wiki: examples_toc
Wiki: updates_to_database