Persisting two entities at the same time
I have been struggling with this for sometime and can't seem to get past the problem. I have a persisted entity called SiteVisit which is many-to-many related to Staff via an intermediate table called SiteVistHasStaff.
Using Netbeans, CRUD and JSf I have been able to populate these tables (using three CRUD pages) with meaningful data and created queries which display site visits for employees etc.
However to improve the user interface I am trying to create a page that allows the booking of a SiteVisit and selecting the Staff who will be attending then creating new records in the SiteVist and SiteVisitHasStaff tables when the page/form is submitted.
This seems such a simple real world task but I cannot seem to get clear the steps I need to take to achieve it. I have managed to get the data onto the same page in a selectManyMenu but then fail with persistence errors when trying to commit my selections(the site visit is created w开发者_Python百科ithout a list of staff but the StaffVisitHasStaff record fails as there is no value for the SiteVisit id field)
Can I use the CRUD creation methods generated by netbeans, which sort of feels like the correct way as I am reusing code, but my thinking is no as they use different EntityManagers and don't appear to know about each other. Do I need to create a new bean (I've tried this unsuccessfully) with a new facade that deals with the requirement? Or is it something to do with my entity definitions.
@OneToMany(cascade = CascadeType.ALL, mappedBy = "siteVisitIdsiteVisit")
private List<SiteVisitHasStaFF> siteVisitHasStaffList;
@JoinColumn(name = "site_visit_idsite_visit", referencedColumnName = "idsite_visit")
@ManyToOne(optional = false)
private SiteVisit siteVisitIdsiteVisit;
Can anyone help or point me in the direction of an example which demonstrates how to do this I have googled, read and tried so many things I am just completely confused. Thanks for any help you can offer.
Well, just a shot in the dark, I'm not that firm with Netbeans/CRUD/whatever, but in which order are you persisting your entities and which persistence error do you get exactly?
As I recall, if you have two different entity managers, initially they don't know entities persistet by the other. Additionally, you have to persist something to reference it.
So if one EM is persisting something, the entity will resist only in his persistence context until everyting is commited (end of transaction, flush,...). The other EM will not automatically detect the entity, that's what merging entities is for .
Don't know what would be applicable in your situation, but I would use one EM for all operations in one scope or merge the entities you want to use into the other EM.
精彩评论