1. 数据库中表的列名和实体类的属性名称不一致。
可以使用 resultMap来解决。
2.在 mybatis 中多对一映射处理
用户表和角色表示多对一的关系
3.java 类结构
用户类:User.java
public class User implements Serializable{ private int id; private String name; private int age; private int roleId; private Role role; 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; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + ", roleId=" + roleId + ", role=" + role + "]"; }}
角色类:Role.java
public class Role { private int id; private String name; 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; } @Override public String toString() { return "Role [id=" + id + ", name=" + name + "]"; }}
4.映射关系----通过sql语句将两张表关联起来
5.测试
@Test public void testFindAll() throws IOException{ SqlSession session = MybatisUtil.getSqlSession(); Listlist = session.selectList("cn.sxt.vo.UserMapper.findAll"); for(User u:list){ System.out.println(u); } session.close(); }