Create table with Foreign Collection Field
foreign-collection, java, ormlite
Solution
So the exception message was designed to help here. To quote it with the class names removed:
Foreign collection class `ContentItem` for field `contentItens` column-name does not contain a foreign field of class `PhytoterapicItem`
That looks to be the case. Whenever you have `ForeignCollection`, the class contained by the collection must have a foreign field back to the parent class.
In your case, `PhytoterapicItem` extends the `DomainItem` class which has a `ForeignCollection` of `ContentItem` objects. That means that `ContentItem` must have a foreign field of type `PhytoterapicItem`. Otherwise, how would ORMLite know which of the `ContentItem` items in the table are associated with a particular `PhytoterapicItem`.
The example of `Account` and `Order` objects in the foreign collection documentation may help you with your schema. Each `Account` has a foreign collection of `Order` objects. Whenever you query for an `Account` a separate query is performed to find the collection of `Order` objects that correspond to a particular `Account`. That means that each `Order` has to have a foreign `Account` object.
Problem
I have this abstract class: DomainItem ``` abstract public class DomainItem { @DatabaseField(generatedId = true) protected long id; @ForeignCollectionField(eager = false) protected ForeignCollection<ContentItem> contentItens; //getters and setters } ``` ContentItem: ``` abstract public class ContentItem { @DatabaseField(generatedId = true) protected long id; @DatabaseField(foreign = true) protected DomainItem domainItem; @DatabaseField() protected String content; //getters and setters } ``` And these (no abstract): ``` @DatabaseTable() public class PhytoterapicItem extends DomainItem{ public PhytoterapicItem(){ } } ``` PhytoterapicContent ``` @DatabaseTable(tableName = "phytoterapiccontent") public class PhytoterapicContent extends ContentItem { @DatabaseField(canBeNull = false) private String defaultName; @DatabaseField(canBeNull = false) private String scientificName; //getters and setters } ``` In my DatabaseHelper I trying create the tables: ``` //DatabaseHelper ... @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { try { Log.i(TAG, "onCreate"); TableUtils.createTable(connectionSource, PhytoterapicContent.class); Log.i(TAG, "Created table PhytoterapicContent"); TableUtils.createTable(connectionSource, PhytoterapicItem.class); Log.i(TAG, "Created table PhytoterapicItem"); catch{ ... } ``` The table PhytoterapicContent is created. But I got the follow error: java.sql.SQLException: Foreign collection class br.com.project.model.ContentItem for field 'contentItens' column-name does not contain a foreign field of class br.com.project.model.PhytoterapicItem