mercoledì 20 aprile 2011

JPA and Many-to-Many relationships

I spent a few days in order to clearly comprehend how JPA really works. In particular I was hesitant about the relation between the User table and the Instructor/Customer tables. After generating the Entity classes from the tables using the guided procedure on Eclipse I discovered that the User entity had a many-to-many relation with Customer and a many-to-many relation with Instructor. I was not sure if it was correct and how I had to manage it, however it turned out that everything was correct and the matter was simpler than I could ever expected.

The relation was clearly many-to-many due to the connection tables user_customer and user_instructor. For this reason the User entity has a Set of Customer entity and a Set of Instructor entity in it. So accessing one of the two, after retrieving the User from the DB using the email as PK, was quite a joke:

User user = em.find(User.class, email);
Customer customer = user.getCustomers().iterator().next();

Et voilà! I have my Customer entity ready for use.

Here are some useful links on the subject:
http://www.giuseppesicari.it/articoli/jpa-java-persistence-api/
http://en.wikibooks.org/wiki/Java_Persistence/Relationships
http://www.oracle.com/technetwork/articles/javaee/jpa-137156.html

Nessun commento:

Posta un commento