0 Replies Latest reply on Jun 19, 2012 11:52 AM by Randahl Fink Isaksen

    JPA: Strategy for creating entity relationships from a client?

    Randahl Fink Isaksen Novice

      Hibernate/JPA on JBoss 7.1.1 surely works amazing. However, I have run into this problem of updating references between entities from my rich client. The situation is this:


      1. I have two entities A and B, where any A always now exactly one instance of B through a many-to-one.

      2. My rich client loads all instances of B from the server at startup.

      3. At some point my client creates a new instance of A, and since all As should know an instance of B, my client chooses a B instance and invokes a.setB(b);


      Now I need to persist the A instance on the server, so I invoke a business method, let's call it persistA(A a) with the A instance as a parameter. But herein lies the rub: Now, not only the A instance is serialized and sent to the server, also the potentially huge B instance is serialized along with A. That was not what I wanted. I just wanted to save A in such a way that it has a relationship with the chosen instance of B. If the A instance takes up 10 bytes and the B instance along with everything it references takes up 10 megabytes, saving all of B just to create the relationship to B seems like overkill.


      I was thinking of changing all my business methods so they carry the ID of B instead, like this

      persistA(A a, String idOfB);

      and then have the server load the B instance b from database using the idOfB and invoke a.setB(b) before persisting A; but I think this raises two new problems:


      1. I now have to load all of B into memory server side even though I just need to persist the instance of A, and I do not need all the information stored in B.

      2. This approach splits the creation of A between the client and the server, such that the client sets all primitive properties of the A instance, while the server sets all relationships. This seems less straight forward, and harder to work with.


      What I was really hoping for was for a feature which would allow me to flush all unnecessary state out of the A instance before invoking my business method. Something like


      A a = new A();





      Here the "MagicWand" would change the A instance in such a way that instead of carrying references to full B instances, A would refer light B proxies carrying only the ID of the B instance. This is not completely nuts, because if I load an A instance from the server, what I get is an A instance with proxy references – *NOT* references to full instances of B (depending on my loading strategy of course).


      Has anyone else been struggling with this, and found a sound approach? Any thoughts or input would be highly appreciated.