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 [id=" + id + ", name=" + name + ", age=" + age + ", roleId=" + roleId + "]"; }}
Role.java
public class Role { private int id; private String name; private Listusers; 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 getUsers() { return users; } public void setUsers(List users) { this.users = users; } @Override public String toString() { return "Role [id=" + id + ", name=" + name + "]"; }}
3.映射文件
4.测试
@Test public 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
UserMapper.xml