Working with Hibernate relationships
I'm working in Hibernate. I got 3 entities, that's the relationship among them:
User 1 -> N Orders 1 -> N Order Details
how could I add a row in table "Order details" of a specific Order for a given User?
I know how to add a new row in table Orders and Order Details, something like that:
User user=(User)session.get(User.class, username);
Order order=new Order();
OrderDetails orderDetails=new OrderDetails();
orderDetails.setAmount(1);
order.addOrderDet开发者_StackOverflow社区ails(orderDetails);
user.addOrder(order);
session.save(user);
transaction.commit();
It is correct?
But what happen when I only want to add a row in table addOrderDetails of a specific Order for a given User? Could i do this?
List<Order> o=session.createCriteria(Order.class)
.add( Restrictions.eq("idUser", User) );
o.get(0).addOrderDetails(orderDetails);
Actually i don't know how to work with tables Orders and Orders details, should i do from User table? How? Using Criteria from User table i only can get a list of users, but can not work with the others tables.
Thanks
If you have mapping that represents your relationship, you can get User and user would have a set or list with elements of type Order. Then you can update the specific order.
Methods that you have described are also correct short of some mistakes (call list()
on criteria to get list for example).
It seems a user may own a lot of resources, if you access orders from the User object, it may impact on the performance.
// user.addOrder(order);
// session.save(user);
order.setUser(user);
session.save(order);
Also remove the orders property from the User class would clean up the design. But again it depends on the business model.
精彩评论