im trying to learn some jsp as well as the spring framework.
My application has 2 sql tables. ‘User’ and ‘Locations’
each Location belongs to a User. The location table has a foreign key referencing the id of the user.
I want to implement my application such that given a user (i.e ‘user1’) i can call user1.getLocations() to retrieve a list of the locations associated with that user, but i do not know where to implement this. (in the User class, on the UserDao, on the UserManager, on the controller for the page that should list all users and their , etc?)??
—-edit:
On the controller:
List<User> users = userManager.getUsers();
for(User user:users) {
user.setLocations(locationManager.getLocations(user));
}
myModel.put("users", users);
return new ModelAndView("location", "model", myModel);
}
is this a conventional solution? locationManager.getLocations(user) returns a List of Locations with the same id as user.
I wouldn’t create a separate DAO-method for handling this, the “user1.getLocations” is the right approach. Hibernate et al. support stuff like lazy-loading and mapping of table relations as Collections (like Lists and Sets) between entities, which are meant for these kind of situations. Here’s a simple example,which might not work out-of-the-box, depending how your tables are named etc., but you’ll get the idea:
Note that you can get the locations from the User-side, even though the relation in the database is only from Location to User (the “mappedBy”-attribute in Users’ @OneToMany actually tells which field on the “other side of the reference” (Location) points to this User).
I’d suggest looking up some JPA and/or Hibernate with Spring -tutorials for more in-depth information.