Java – ormlite – how to create objects and populate external collections?

I'm trying to create an object and populate the members of the external collection held by the object in an operation I've tried every sequence I can think of, and it doesn't seem to work

My course is (skip irrelevant fields and comments):

@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 object this way:

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've tried all sorts of the last three statements, but it doesn't seem to work: in each case, the 'job of the entry in the scheduled job task database table_ ID 'fields are null

What did I do wrong?

Solution

What you are missing is that you have not set a task Job field ScheduledJobTask. The job field is used to set the external collection When you retrieve a job, it looks up all the tasks with the job in the task table – not vice versa

You will need to do the following:

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 job fields will have jobs with ID fields set So when you stick to your task, they will have this position in their field of work

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>