java- stick with the sleep / JPA

I've been working on JBoss with hibernate / JPA together for a few months, but there is one question I can not find an answer or solution.

 

It seems when you create a new entity bean, I at least call EntityManager.persist (entityBean) before executing the query can not be otherwise, the following error occurs:

TransientObjectException: transient object references an instance of unsaved - save the transient instance before refresh

one example:

 

Job job = new Job();
Collection<Task> tasks = job.getTasks();
//entityManager.persist(job);
ActionPlan actionPlan = (ActionPlan) entityManager.createNamedQuery("ActionPlan.findByCommand").
                setParameter("type", RunOperation.Install).getSingleResult();
Task task = Task.getTask(actionPlan);
task.setActionPlan(actionPlan);
tasks.add(task);
task.setJob(job);

My question is, if you do not first reserves "job" (commented-out line), you can not call createNamedQuery. ActionPlan and Job are related, but NamedQuery (findByCommand) Job is not on the coupling. Bothers me is that when the newly created when the Job in this case does not even make sense, so I need to keep Job query the database.
the persist () calls will be moved to the end of the code segments will generate the above error.

I know I'm working on an object is not persistent, but persistent so that if an error can not be rolled back.

I believe there is a solution, so if someone got the answer, I would be very grateful. What am I missing?

Best answer

It can not seem to query the database content is not reasonable, right? You can do is to start using a transaction. In a simple case, your session will have a transaction that will remain open until you close the session. By then the transaction will be submitted, all your changes will be preserved. You need to do is roll back the transaction when an error occurs.

 

PS Here at the bottom you can find the "typical transaction should use the following idiom."

 

Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
    //do some work
    ...
    tx.commit();
}
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
}
finally {
    sess.close();
}
Published 566 original articles · won praise 0 · Views 2819

Guess you like

Origin blog.csdn.net/weixin_44109689/article/details/103996718
Recommended