hyljava

Spring MVC级联查询(用户与地址之间关系)

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

posted on 2013-04-12 13:10 何云隆 阅读(3918) 评论(3)  编辑  收藏 所属分类: Spring MVC

评论

# re: Spring MVC级联查询(用户与地址之间关系) 2015-12-29 11:55 啊啊啊啊

死死死死死死死  回复  更多评论   

# re: Spring MVC级联查询(用户与地址之间关系) 2015-12-29 11:55 啊啊啊啊

发错了  回复  更多评论   

# re: Spring MVC级联查询(用户与地址之间关系) 2015-12-29 11:55 啊啊啊啊

不好意思  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: