这里的级联查询仿照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=王武]]]]