views:

36

answers:

1

Hello!

I am using the Java Enterprise Edition with JPA(Hibernate) for a Server-Client application (via EJB). The program stores a lot of data in a database that needs to be transfered to the client. Because I want to transfer as less data as possible I do not want to transfer objects twice.

I want to demonstrate my problem with a small example:

Database:

[User]
- UserID (PK)
- Name
- Adress (FK)

[Adress]
- AdressID (PK)
- Street

Sample data:
[User:1, Max, 1]
[User:2, Peter, 2]
[Adress:1, Mainstreet]
[Adress:2, Riverstreet]

Now I want to transfer a list of all users (with eager loading of Adress) to the client and also a list of all Adresses.

Server side creation of the lists:

Userlist:

Query q = manager.createQuery("select u from UserBean m LEFT JOIN FETCH u.adress");
List<UserBean> l = (List<UserBean>) q.getResultList();
return l;

Adresslist:

Query q = manager.createQuery("select a from AdressBean m");
List<AdressBean> l = (List<AdressBean>) q.getResultList();
return l;

When the client gets the lists I check the hashcodes of user1.getAdress().hashCode() and adress1.hashCode(). The result is that it is not equal so that the object must have been saved twice and also be transfered twice while getting the lists.

Is it possible to tell (maybe in the EJB) to transfer objects only once and to to transfer the right references? Or can I improve my transfer mechanism?

Many thanks! Peter31280

+2  A: 

You can't transfer the same instances, if your client is running in a different VM. Deserialization by default creates new instances of the objects.

So you'd best override hashCode() and equals() on your classes.

Bozho
what else :) +1
Pascal Thivent