GWT + Hibernate + saving bandiwidth
I am writing a gwt app using hibernate to save on the server.
I have a similar concept to customer -> orders. So if I create the class customer and the class orders, the in the database, the order table has a foreign key to the customer table.
Say I wanted to retrieve the orders from the server, and I do not care about the customer. If I write something to bring down the orders, it would automatically bring down the customer with it if I use EAGER loading. If I do not want that, then I can leave it as lazy loading and just get the orders, and I assume that myOrder.getCustomer() == null.
Now if I wanted to create an order on the client, is there a way to set the customerid on the order and then pass it up to save without having to pass up the customer object with it. i.e.
Order myOrder = new Order();
.
.
.
myOrder.setCustomerID("1234");
rpcSave(myOrder);
Or is the only 开发者_如何学JAVAoption I have
Customer me = new Customer()
Order myOrder = new Order()
.
.
.
myOrder.setCustomer(me);
rpcSave(myOrder);
Thanks,
Nadin
One options is to use a transient field in the Customer that is linked to the Order:
public class Order {
@Transient
private String customerId;
...
// setter/getter methods
}
Here is how the value would be used on the client:
Order myOrder = new Order();
...
myOrder.setCustomID("1234");
rpcSave(myOrder);
Here is how the value would be used on the server:
if (order.getCustomerId() != null) {
Customer customer = // lookup customer by primary key
order.setCustomer(customer);
}
This logic allows the client to create the link between order and customer without requiring the Custom object itself. The server code, on the other hand, would be tasked with looking up the Customer instance and adding it to the actual Order.
The problem with this approach is that it adds attributes and methods to the Order object that do not always serve a purpose and make the code harder to follow.
An alternative approach would be to change the rpcSave operation to take in an Order and a customerId. The server would lookup the Customer based on the id and make the association itself. Thereby saving the overhead of the data transmission, while keeping your Order object simple:
// client
Order myOrder = new Order();
...
rpcSave("1234", myOrder);
// server
Customer customer = // find customer by customerID;
newOrder.setCustomer(customer);
...
Hope this helps.
精彩评论