I designed a model with two entities : ParentEntity and ChildEntity. I use OrmLite to store them in a database.
I actually get my data from a remote webservice. This is the process I have :
- Request the webservice (using retrofit)
- Get JSON string in response
- JSON string is parsed to JSON model by Gson (thank you again retrofit :))
- I convert JSON model to an OrmLite model (no library, I make it myself)
- The OrmLite model is given back to the callback waiting for the response of the request
- The callback is in charge of calling the DAO to actually store the data
This process works perfectly for simple entities. But a problem appears when I try to manage more complex entities, with a ForeignCollection for example. Actually, I can't achieve the step 4 because I can't create a new ForeignCollection to put my child entities inside it.
I found some answers saying that I should store every child myself, but it will break the step 6 of my workflow.
So the question is :
How can I initialize the ForeignCollection before getting the object from the database ?
I could find a way to change the workflow. But it's only a kind of "work-around" and will create container objects just to achieve this...
The OrmLite schema (simplified)
(The class Entity just have a property id and its getter/setter.)
ParentEntity
@DatabaseTable(daoClass = ParentEntityDao.class)
public class ParentEntity extends Entity
{
@ForeignCollectionField(eager = true)
private ForeignCollection<TimesheetEntry> entries;
public Collection<TimesheetEntry> getEntries()
{
if(entries != null)
{
return Collections.unmodifiableCollection(entries);
}
else
{
return Collections.unmodifiableCollection(new ArrayList<TimesheetEntry>());
}
}
public void addEntry(ChildEntry childEntry)
{
childEntry.setParent(this);
entries.add(childEntry);
}
public void removeEntry(ChildEntry childEntry)
{
entries.remove(childEntry);
}
}
ChildEntity
@DatabaseTable(daoClass = ChildEntityDao.class)
public class ChildEntry extends Entity
{
@DatabaseField(foreign = true, canBeNull = false)
private ParentEntity parentEntity;
public void setParentEntity(ParentEntity parentEntity)
{
this.parentEntity = parentEntity;
}
public ParentEntity getParentEntity()
{
return parentEntity;
}
}
JSON schema (simplified)
Parent entity
public class JsonParentEntity
{
private List<JsonChildEntity> entries;
// Getter/setter
}
Child entity
public class JsonChildEntity
{
private String name;
// Getter/setter
}