Spring MVC級聯(lián)查詢(用戶與地址之間關(guān)系)
這里的級聯(lián)查詢仿照Hibernate中的一對多關(guān)系映射,寫個例子留個筆記(地址表主表,用戶表從表)
用戶表(類)User
成員變量如下,并且對應(yīng)有g(shù)et和set方法
private String uId;
private String uUserName;
private String uPassWord;
private String uTelephone;
private int uAge;
private Date uBirthday;
對應(yīng)的表如下:
對應(yīng)的表如下:

private int no;
private String name;
private List<User> userList;

對應(yīng)的UserDao中先寫:

對應(yīng)的UserDao中先寫:
public List<User> findByAddressId(int a){
String sql="select * from usermbo where address=?";
List<User> users = new ArrayList<User>();
Object[] params=new Object[]{a};
users = jdbcTemplate.query(sql,params, new UserRowMapper() );
return users;
}
private class UserRowMapper implements ParameterizedRowMapper<User>{
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setuUserName(rs.getString("username"));
user.setuAge(rs.getInt("age"));
user.setuId(rs.getInt("id")+"");
user.setuTelephone(rs.getString("telephone"));
return user;
}
}
此部完成以后,再寫AddressDao
此部完成以后,再寫AddressDao
@Autowired
private UserDao userDao ;
public List<Address> getAddress(){
String sql="select * from address";
List<Address> addresss = new ArrayList<Address>();
addresss = jdbcTemplate.query(sql, new AddressRowMapper() );
return addresss;
}
private class AddressRowMapper implements ParameterizedRowMapper<Address>{
public Address mapRow(ResultSet rs, int rowNum) throws SQLException {
Address address=new Address( );
address.setNo(rs.getInt("no"));
address.setName(rs.getString("name"));
address.setUserList( userDao.findByAddressId(rs.getInt("no")));
return address;
}
}
Service層再配一下(此層不配也行直接將
@Autowired
private AddressDao addressDao ;引入Controllar中即可)
在Controllar中再寫
Service層再配一下(此層不配也行直接將
@Autowired
private AddressDao addressDao ;引入Controllar中即可)
在Controllar中再寫
addressService.getAddress()就可以查出結(jié)果
[Address [name=計算力, no=1, userList=[User [uAddress=null, uAge=12, uBirthday=null, uId=11, uPassWord=null, uTelephone=1234567, uUserName=張三]]], Address [name=大連, no=2, userList=[]], Address [name=海南, no=3, userList=[User [uAddress=null, uAge=34, uBirthday=null, uId=12, uPassWord=null, uTelephone=2323232323, uUserName=李四], User [uAddress=null, uAge=33, uBirthday=null, uId=13, uPassWord=null, uTelephone=2323, uUserName=王武]]]]
posted on 2013-04-12 13:10 何云隆 閱讀(3925) 評論(3) 編輯 收藏 所屬分類: Spring MVC