We'll start by fetching an object (Issue, in our case) by its Id. First, if we find that our table has not the same name as our entity to retrieve. We'll have to customize this using OrmConfiguration.tableAlias() method. Also, this implies the object must have an Id attribute and the table must have an Id column. Let's suppose this is the case. We must specify this in the configuration, using setDefaultIdAttribute() method in OrmConfiguration. So, we change our IssuesDb.configureOrm() method:
@Override
protected void configureOrm(final OrmConfiguration ormConfig) {
ormConfig
.idAttributeIs("id")
.entity(Issue.class).mapsToTable("issues");
}
This will tell the ORM that all classes with an Id attribute will use it as a primary key.
And done! we can start fetching objects. Let's see how:
final Issue issue = new IssuesDb().orm().loadById(Issue.class, 1);
Ok. If you tried this example, you'll find out that a Issue is retrieved, but the id of the object (not the row in the database) is null. That's because Issue have an issueId attribute, not an id attribute. Let's fix this using the setIdAttribute() method (to tell MILK this is the primary key attribute) and attributeAlias() to add a custom mapping:
@Override
protected void configureOrm(final OrmConfiguration ormConfig) {
ormConfig
.idAttributeIs("id")
.entity(Issue.class)
.mapsToTable("issues")
.idAttributeIs("issueId")
.mapsAttribute("issueId").with("id");
}
If you try again, your issue object will be correctly retrieved.
You have to keep in mind something: MILK will map the columns to the attributes of the object by name or custom mapping. If an attribute is not found for a given column, it will simply not try to set its value
And another thing: MILK will only set non transient fields, using their set methods
So, done. We have retrieved our first object from the database using its Id. Now, what if we want to use a complex condition? Let's use filters!