java之mybatis之字段映射及多对一

时间:2022-09-24 14:40:46

1. 数据库中表的列名和实体类的属性名称不一致。

可以使用 resultMap来解决。

    <select id="findAll" resultMap="UserMap">
        select id,userName,age from t_user
    </select>
    <resultMap type="User" id="UserMap">
        <!--id映射主键 property是实体类的属性名 column是表中的列名  -->
        <id property="id" column="id"/>
        <result property="name" column="userName"/>
        <result property="age" column="age"/>
    </resultMap>

2.在 mybatis 中多对一映射处理

用户表和角色表示多对一的关系

java之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语句将两张表关联起来

<mapper namespace="cn.sxt.vo.UserMapper">
    <select id="findAll" resultMap="UserMap">
        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 </select>
    <resultMap type="User" id="UserMap">
        <id property="id" column="uid"/>
        <result property="name" column="uname"/>
        <result property="age" column="uage"/>
        <result property="roleId" column="roleId"/>
        <!-- 映射关联对象 -->
        <association property="role" column="roleId" javaType="Role">
            <id property="id" column="roleId"/>
            <result property="name" column="rname"/>
        </association>
    </resultMap>
</mapper>

5.测试

  @Test
    public void testFindAll() throws IOException{
        SqlSession session = MybatisUtil.getSqlSession();
        List<User> list = session.selectList("cn.sxt.vo.UserMapper.findAll");
        for(User u:list){
            System.out.println(u);
        }
        session.close();
    }