Mybatis入门之 resultMap的映射关系

当查询的数据表的字段名与pojo类的属性名一致时,可以用resultType,但sql查询到的字段与pojo的属性名不一致时,则需要使用resultMap将字段名和属性名对应起来。
resultType直接表示返回类型,
resultMap:对外部resultMap的引用,二者不能同时存在。

前期准备,一个employee表,项目的目录结构与之前写的两篇文章一致。

CREATE TABLE employee(
 id int(11) NOT NULL auto_increment,
 user_name VARCHAR(50) NOT NULL,
 age int(6) NOT NULL,
 email VARCHAR(50) NOT NULL,
 PRIMARY KEY(id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

@Data
public class Employee {
    private Integer id;
    private String userName;
    private Integer age;
    private String email;  
}

单表查询

EmployeeMapper接口:

public Employee getEmpById(Integer id);

EmployeeMapper.xml映射文件:

<mapper namespace="com.diligentkong.mybatis.dao.EmployeeMapper">

    <!--resultMap 自定义某个javaBean的封装规则, type:自定义规则的java类型 id“唯一标识,方便引用-->
    <resultMap type="com.diligentkong.mybatis.bean.Employee" id="simpleEmp">
       <!-- 指定主键列的封装规则:与下面<result>标签的区别是可以用于提升性能,所以这里用<id>标签来定义主键的映射关系
            column:数据库中对应的字段名
            property:对应JavaBean 的属性名
       -->
        <id column="id" property="id"></id>
       <!-- 定义普通列封装规则-->
        <result column="user_name" property="userName"></result>
        <!-- 其他不指定的列会自动封装:我们只要写resultMap就把全部的映射规则都写上。 -->
        <result column="age" property="age"></result>
        <result column="email" property="email"></result>
    </resultMap>

    <select id="getEmpById" resultMap="simpleEmp" >
        select * from employee where id=#{id};
    </select>


</mapper>

测试结果:

 public SqlSessionFactory getSqlSeeionFactory() throws IOException {
        String resource = "config/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);

    }

    @Test
    public void myTest() throws IOException {
        // 1.获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = getSqlSeeionFactory();
        // 2、获取sqlSession对象
        SqlSession openSession = sqlSessionFactory.openSession();

        try {
            // 3、获取接口的实现类对象
            //会为接口自动的创建一个代理对象,代理对象去执行增删改查方法

            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            Employee employee = mapper.getEmpById(1);
            System.out.println(employee);

            openSession.commit();
        } finally {
            openSession.close();
        }
    }

}

结果:Employee(id=1, userName=张三, age=20, email=zhangsan.163com)

association 用于一对一,一对多

关联查询:association 用于一对一,一对多的情况
现在我有这样的需求,一个Employee 员工对应一个dept部门,而这个dept部门也有员工(employee) 信息
新建一个dept表,

CREATE TABLE dept(
id int(11) NOT NULL auto_increment,
dept_name VARCHAR(50) NOT NULL,
PRIMARY KEY(id) 
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO dept VALUES(1,"研发部");
INSERT INTO dept VALUES(2,"测试部");
INSERT INTO dept VALUES(3,"市场部");

在employee表中添加dept_id字段,建立外键关系。

alter table employee add column d_id INT(11)
ALTER table employee ADD constraint fk_emp_dept FOREIGN KEY(dept_id) REFERENCES dept(id);
INSERT INTO employee VALUES(1,"张三",20,"zhangsan.163com",1);
INSERT INTO employee VALUES(2,"李四",21,"lisi.163com",1);
INSERT INTO employee VALUES(3,"王五",22,"wangwu.163com",2);
INSERT INTO employee VALUES(4,"赵六",23,"zhaoliu.163com",3);
INSERT INTO employee VALUES(5,"kong",20,"kong.163com",3);

新建Department 类

@Data
public class Department {
    private Integer id;
    private String deptName;
   
}

Employee类中新增dept属性

@Data
public class Employee {
    private Integer id;
    private String userName;
    private Integer age;
    private String email;
    private Department dept;

}

public Employee getEmpAndDept(Integer id);

EmployeeMapper接口:

public Employee getEmpAndDept(Integer id);

EmployeeMapper.xml映射文件:

 <resultMap id="MyDeptEmp" type="com.diligentkong.mybatis.bean.Employee">
      <id column="id" property="id"></id>
      <result column="user_name" property="userName"></result>
      <result column="age" property="age"></result>
      <result column="email" property="email"></result>

      <!--  association可以指定联合的javaBean对象
property="dept":指定哪个属性是联合的对象
javaType:指定这个属性对象的类型[不能省略]
-->
      <association property="dept" javaType="com.diligentkong.mybatis.bean.Department">
          <id column="id" property="id"/>
          <result column="dept_name" property="departmentName"/>
      </association>

  </resultMap>
  <select id="getEmpAndDept" resultMap="MyDeptEmp">
      select e.id id, e.user_name user_name, e.age age, e.email email,e.dept_id deptid,
      d.id id,d.dept_name dept_name from employee e,dept d where e.dept_id=d.id AND e.id= #{id}
  </select>

测试结果:

Employee employee = mapper.getEmpAndDept(1);
System.out.println(employee);
结果:
Employee(id=1, userName=张三, age=20, email=zhangsan.163com, dept=Department(id=1, departmentName=研发部))

collection 用于 一对一 和 一对多

查询部门信息,并查询部门中包含的员工信息,修改pojo

@Data
public class Department {
    private Integer id;
    private String departmentName;
    private List<Employee> emps;

}

DepartmentMapper接口:

public Department getDeptById(Integer id);

DepartmentMapper.xml映射文件

<mapper namespace="com.diligentkong.mybatis.dao.DepartmentMapper">

    <resultMap id="MyDept" type="com.diligentkong.mybatis.bean.Department">
        <id column="did" property="id"></id>
        <result column="dept_name" property="departmentName"></result>
        <!--
           collection定义关联集合类型的属性的封装规则
           ofType:指定集合里面元素的类型
       -->
        <collection property="emps" ofType="com.diligentkong.mybatis.bean.Employee">
            <!-- 定义这个集合中元素的封装规则 -->
            <id column="id" property="id"/>
            <result column="user_name" property="userName"/>
            <result column="age" property="age"/>
            <result column="email" property="email"/>
        </collection>
    </resultMap>


    <select id="getDeptById" resultMap="MyDept">
		SELECT d.id did,d.dept_name dept_name,
				e.id eid,e.user_name user_name,e.age age,e.email email
		FROM dept d
		LEFT JOIN employee e
		ON d.id=e.dept_id
		WHERE d.id=#{id}
	</select>
</mapper>

测试结果:

 DepartmentMapper dept = openSession.getMapper(DepartmentMapper.class);
 Department department = dept.getDeptById(1);
 System.out.println(department);
 结果:
 Department(id=1, departmentName=研发部, emps=[Employee(id=null, userName=张三, age=20, email=zhangsan.163com, dept=null), Employee(id=null, userName=李四, age=21, email=lisi.163com, dept=null)])


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用Mybatis创建resultMap映射是很简单的,你只需要在映射文件中使用<resultMap>标签即可。例如: ``` <resultMap id="userMap" type="User"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="password" property="password" /> </resultMap> ``` 这里我们创建了一个名为"userMap"的resultMap,它映射了一个名为"User"的实体类。其中,<id>标签表示实体类中的主键属性,<result>标签则表示实体类中的普通属性。 要创建一个查询语句,使用这个resultMap,你只需要在<select>标签中引用这个resultMap即可。例如: ``` <select id="selectUser" resultMap="userMap"> SELECT id, username, password FROM user WHERE id = #{id} </select> ``` 这里我们创建了一个名为"selectUser"的查询语句,它使用了前面定义的"userMap"作为结果集映射。这个查询语句将返回一个id等于指定值的用户对象。 ### 回答2: 使用MyBatis创建resultMap可以通过以下步骤实现: 1. 在MyBatis的配置文件(通常是`mybatis-config.xml`)中配置typeAliases,用于将Java类别名映射到SQL结果集中的列名。例如: ``` <typeAliases> <typeAlias type="com.example.User" alias="User"/> </typeAliases> ``` 2. 在映射文件(通常是`mapper.xml`)中创建resultMap元素。resultMap用于定义Java对象和SQL结果集之间的映射关系。例如: ``` <resultMap id="userMap" type="User"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> </resultMap> ``` 在上面的例子中,`id`属性将Java对象的`id`字段与SQL结果集中的`id`列进行映射;`name`和`age`属性分别映射到对应的列。 3. 在映射文件中使用resultMap引用已创建的resultMap。例如: ``` <select id="getUserById" resultMap="userMap"> SELECT id, name, age FROM user WHERE id = #{id} </select> ``` 在上面的例子中,`getUserById`是一个查询语句,它使用了之前创建的`userMap` resultMap。 通过以上步骤,我们可以使用MyBatis创建resultMap来实现Java对象和SQL结果集之间的映射关系,从而方便地操作数据库。 ### 回答3: 使用MyBatis创建结果映射ResultMap)是为了将查询结果集中的列映射Java对象的属性上。通过创建ResultMap,可以方便地将数据库中的数据封装到Java对象中。 下面是使用MyBatis创建ResultMap的步骤: 1. 在mybatis-config.xml文件中配置MyBatis的数据源和其他相关配置。 2. 在映射文件(Mapper)中编写SQL语句,包括查询语句以及对应的列名。 3. 在映射文件中通过<ResultMap>标签创建ResultMap,指定Java对象的类型以及与数据库列的映射关系。 示例代码如下: <resultMap id="userMap" type="com.example.User"> <id property="id" column="user_id"/> <result property="username" column="user_name"/> <result property="age" column="user_age"/> </resultMap> 在上面的代码中,id属性指定了Java对象的属性名,column属性指定了数据库中对应的列名。 4. 在映射文件中使用<select>标签进行查询操作,并在标签内使用<resultMap>指定ResultMap的id。 示例代码如下: <select id="getUser" resultMap="userMap"> SELECT * FROM user WHERE user_id = #{id} </select> 在上面的代码中,resultMap属性指定了ResultMap的id,即userMap。 通过以上步骤,就成功创建了一个ResultMap映射查询结果集到Java对象中。 需要注意的是,这只是最基本的创建ResultMap的示例,实际开发中还可以使用其他一些高级特性来处理复杂的映射逻辑,比如使用association和collection等标签来处理一对一和一对多的关系

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值