I'm building an application using Java2EE, and I have several Entities including this two:
Entity Product (Snippet):
@Entity
public class Product implements Serializable {
@ManyToMany(mappedBy = "products")
private List<KB> kbs;
public List<KB> getKbs() {
return kbs;
}
}
Entity KB ( K nowledge B ase article) (Snippet):
@Entity
public class KB implements Serializable {
@ManyToMany
private List<Product> products;
}
Has you can tell, they are bidirectionally related, so JPA created three tables: Product, KB, and KB_Product.
I also have EJB's and Managed Beans to access the data persisted by this Entities, here's a snippet of the code I use to retrieve the list of associated KB's with a particular Product:
@SessionScoped
public class ProductController {
private List<KB> associatedKBs;
public List<KB> getAssociatedKBs() {
this.associatedKBs = current.getKbs();
return associatedKBs;
}
}
Everything works OK: When I associate a Product to a KB it g开发者_如何学Goet's inserted in the database (KB_Product table), but (and here's the problem) the getKBs() method only returns updated data the first time it's called.
Example:
1. I create a product named "Computer". 2. I create a new KB article, and associate "Computer" with this KB. 3. This association gets persisted in the KB_PRODUCT table. 4. getKBs() is called by the first time. Everything shows up OK. 5. I create a second KB article, and associate it with "Computer". 6. This association gets persisted in the KB_PRODUCT table. 7. getKBs() is called again but only returns the first association, until I re-deploy the application. After re-deployment, everything shows up.Edit: At first I thought it was a session problem. Turns out that logging out of the application and logging in again doesn't solve the issue, only re-deploying.
Thanks in advance!
Finally I've discovered the EntityManager.flush() method, and it did the trick.
References: http://www.manning-sandbox.com/thread.jspa?threadID=26541&tstart=-1
精彩评论