Being new to JPA programming I still don't feel like I fully understand all of the subtleties yet.
I have been implementing examples from Pro JPA 2 to understand how it all works, but there is one case that I can't figure out how to properly populate the database with.
The example uses two classes a print job and a print queue
@Entity
public class C5E05PrintJob
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
//
@ManyToOne
private C5E05PrintQueue printQueue;
..
(Getters and setters for fields)
..
}
@Entity
public class C5E05PrintQueue
{
@Id private String name;
//
@OneToMany(mappedBy="printQueue")
@OrderColumn(name="PRINT_ORDER")
private List<C5E05PrintJob> jobs;
//
public C5E05PrintQueue(String name)
{
this.name=name;
}
public void addPrintJob(C5E05PrintJob job)
{
if(jobs==null)
{
this.jobs=new ArrayList<C5E05PrintJob>() {};
}
boolean result=this.jobs.add(job);
}
...
(Getters and setters for fields)
}
I created a Servlet where I try to add 3 jobs to the Queue.
Note that the DB classes get an entity manager, call persist and handle rolling back if the persist fails.
C5E05PrintQueue queue=new C5E05PrintQueue("Queue 1");
//
C5E05PrintJob job1=new C5E05PrintJob();
C5E05PrintJob job2=new C5E05PrintJob();
C5E05PrintJob job3=new C5E05PrintJob();
//
queue.addPrintJob(job1);
queue.addPrintJob(job2);
queue.addPrintJob(job3);
//
C5E05PrintJobDB.insert(job1);
C5E05PrintJobDB.insert(job2);
C5E05PrintJobDB.insert(job3);
C5E05PrintQueueDB.insert(queue);
This creates 2 tables in the database (MySQL)
c5e05printqueue with the following values
Name
---------
Queue 1
and c5e05printjob
ID PRINTQUEUE_NAME PRINT_ORDER
--- ------------------------------ ----------------------
1201 NULL 0
1202 NULL 1
1203 NULL 2
The print order column is populated correctly here.
And if I try to add the queue to the database first so the foreign key exists before adding the jobs
C5E05PrintQueue queue=new C5E05PrintQueue("Queue 1");
//
C5E05PrintJob job1=new C5E05PrintJob();
C5E05PrintJob job2=new C5E05PrintJob();
C5E05PrintJob job3=new C5E05PrintJob();
C5E05PrintQueueDB.insert(queue);
job1.setPrintQueue(queue);
C5E05PrintJobDB.insert(job1);
job2.setPrintQueue(queue);
C5E05PrintJobDB.insert(job2);
job3.setPrintQueue(queue);
C5E05PrintJobDB.insert(job3);
The PRINT_ORDER is not filled in properly
ID PRINTQUEUE_NAME PRINT_ORDER
--- ------------------------------ ----------------------
1201 Queue 1 NULL
1202 Queue 1 NULL
1203 Queue 1 NULL
I almost feel like I have a chicken or an egg problem here.
Thanks for any help.