這里的級聯查詢仿照Hibernate中的一對多關系映射,寫個例子留個筆記
(地址表主表,用戶表從表)
用戶表(類)User
成員變量如下,并且對應有get和set方法
private String uId;
private String uUserName;
private String uPassWord;
private String uTelephone;
private int uAge;
private Date uBirthday;
對應的表如下:
地址表(類)Address成員變量如下:
private int no;
private String name;
private List<User> userList;

對應的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
@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中再寫
addressService.getAddress()就可以查出結果
[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=王武]]]]