javasqliteormliteforeign-collection

How to persist a ForeignCollection with ormlite 4.42?


I'm trying to persist a lazy ForeignCollection with ormlite 4.42 and sqlite on a desktop application.

I have an Event class that holds a collection of EventDate :

@DatabaseTable(tableName = "event")
public class Event extends BaseDaoEnabled<Event, Integer> implements Scrap {

     @DatabaseField(generatedId = true, columnName = "_id")
     private int id;

     @ForeignCollectionField(eager = true)
     private ForeignCollection<EventDate> dates;

}

The EventDate class is :

@DatabaseTable(tableName = "eventdate")
public class EventDate extends BaseDaoEnabled<EventDate, Integer> {

    @DatabaseField(generatedId = true, columnName = "_id")
    int id;

    @DatabaseField(canBeNull = true, foreign = true)
    Event event;

}

And here is the code I use to add the EventDates and persist them :

    Event e2 = eventDao.queryForId(id));

    e2.getDates().clear();
    for (final EventDate date : dates) {
        e2.getDates().add(date);
        e2.getDates().update(date);
    }
    e2.update();

The EvenDates are correctly added in the sqlite table, but the field event_id is null : the EventDates are not linked to the Event.

I have no error message. What am I doing wrong ?

Note : I tried with eager collection (adding e2.getDates().updateAll()) but it doesn't work either.


Solution

  • Maybe there is a missing feature here. Right now you need to assign the event on the dates by hand before adding them to the dates collection:

    e2.getDates().clear();
    for (final EventDate date : dates) {
        // this is necessary unfortunately
        date.setEvent(e2);
        e2.getDates().add(date);
    }
    

    I've added the following ticket for review:

    https://sourceforge.net/p/ormlite/feature-requests/31/