androidormliteforeign-collection

ORMLite collection of entities without reference


I want to add an Attachment entity which I will be refering to from multiple different Entities, but it does not refer back to these, how do I get this working in ORMLite?

I keep getting this Exception:

 Caused by: java.sql.SQLException: Foreign collection class entity.Attachment for
    field 'attachments' column-name does not contain a foreign field named
    'attachmentId' of class enity.News

For example I have a News Entity

@DatabaseTable
public class News extends Record {

    @DatabaseField(index = true, id = true)
    private long newsArticleId;
    @DatabaseField
    private String subject;
    @DatabaseField
    private String content;

    @ForeignCollectionField
    Collection<Attachment> attachments;
}

The Attachment Entity:

@DatabaseTable
public class Attachment extends Record {

    @DatabaseField(id = true, index = true)
    private long attachmentId;

    @DatabaseField
    private String attachmentUrl;
}

Could someone please point to me and laugh and tell me why I am doing this wrong and what I'm misunderstanding here. Thanks.


Solution

  • This is a FAQ. To quote from the ORMLite docs on foreign-collections:

    Remember that when you have a ForeignCollection field, the class in the collection must (in this example Order) must have a foreign field for the class that has the collection (in this example Account). If Account has a foreign collection of Orders, then Order must have an Account foreign field. It is required so ORMLite can find the orders that match a particular account.

    In your example, for ORMLite to figure out which Attachments a particular News entity has, the Attachment entity must have a News field. The other way to do would be to have a join table, but ORMLite won't do that for you.