java之mybatis之一对多关联映射
1.在一对多的关联映射中,表结构如下
2.实体类结构
User.java
public class User implements Serializable{private int id;
private String name;
private int age;
private int roleId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return "User [>;
}
}
Role.java
public class Role {private int id;
private String name;
private List<User> users;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
@Override
public String toString() {
return "Role [>;
}
}
3.映射文件
<mapper namespace="cn.sxt.vo.RoleMapper"><select >
select u.id as uid,u.name as uname,u.age as uage,
roleId,r.name as rname from t_user u,t_role r
where u.roleId=r.id and r.id=#{id}
</select>
<resultMap type="Role" >
<id property="id" column="roleId"/>
<result property="name" column="rname"/>
<collection property="users" ofType="User">
<id property="id" column="uid"/>
<result property="name" column="uname"/>
<result property="age" column="uage"/>
<result property="roleId" column="roleId"/>
</collection>
</resultMap>
</mapper>
4.测试
@Testpublic void testFindById() throws IOException{
SqlSession session = MybatisUtil.getSqlSession();
Role role = (Role)session.selectOne("cn.sxt.vo.RoleMapper.findById",2);
System.out.println(role.getId()+"-----"+role.getName());
for(User u:role.getUsers()){
System.out.println(u);
}
session.close();
}
5.使用2个映射语句实现映射
RoleMapper.xml
<select >select * from t_role where id=#{id}
</select>
<resultMap type="Role" >
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- javaType指property的类型 不要忘了写column-->
<collection property="users" column="id" javaType="list"
ofType="User" select="cn.sxt.vo.UserMapper.findUserByRoleId"
></collection>
</resultMap>
UserMapper.xml
<mapper namespace="cn.sxt.vo.UserMapper"><select >
select * from t_user where roleId=#{roleId}
</select>
</mapper>
以上是 java之mybatis之一对多关联映射 的全部内容, 来源链接: utcz.com/z/391787.html