Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORMLite - how to create an object and populate foreign collection?

I'm trying to create an object and populate members of a foreign collection held by that object in a single operation. I've tried every ordering of operations I can think of, and just can't seem to get it to work.

My classes are (skipping irrelevant fields and annotations):

@DatabaseTable
public class ScheduledJob
{
    @DatabaseField(id=true)
    private String id = UUID.randomUUID ().toString ();

    @ForeignCollectionField(eager=true)
    private Collection<ScheduledJobTask> tasks;

    /* other stuff here ... */
}

@DatabaseTable
public class ScheduledJobTask
{
    @DatabaseField(id=true)
    private String id = UUID.randomUUID ().toString ();
    @DatabaseField(foreign=true)
    private ScheduledJob job;
    /* more other stuff ... */

    public ScheduledJobTask(Task t) { 
       /* initialise scheduled task from template task by copying relevant fields...*/ 
    }

}

I create my objects thus:

ScheduledJob job = new ScheduledJob ();
// fill in other fields of job here
job.tasks = new ArrayList<ScheduledJobTask> ();
for (Task t : template.getTasks())
    job.tasks.add(new ScheduledJobTask(t));

sched.getSchedule().add (job);  // 'sched' is an object loaded from another table, this
                                // adds 'job' to a foreign collection in that table
Storage.store.scheduledJobs.createIfNotExists (job);
for (ScheduledJobTask t : job.getTasks ())
    Storage.store.scheduledJobTasks.createIfNotExists (t);
Storage.store.daySchedules.update (sched);

I have tried all orderings of the last three statements, but nothing seems to work: in every case, the entries that end up in the scheduledjobtask database table have null for their 'job_id' field.

Any ideas what I've done wrong?

like image 280
Jules Avatar asked Feb 11 '13 19:02

Jules


1 Answers

What you are missing is that you are not setting the Task.job field. The ScheduledJobTask.job field is what sets up the foreign collection. When you retrieve a Job, it looks in the task table to find all of the tasks that have that job -- not the other way around.

You will need to do something like:

for (Task t : template.getTasks()) {
    t.setJob(job);
    job.tasks.add(new ScheduledJobTask(t));
}

Then, when you do this:

Storage.store.scheduledJobs.createIfNotExists (job);

all of the job fields will have a Job that has an id field set. So when you persist your tasks, their job fields will have that job id.

like image 184
Gray Avatar answered Nov 05 '22 19:11

Gray