resultMap处理复杂映射问题

resultMap复杂映射问题

在这里插入图片描述

association:关联(多对一的情况)

collection: 集合(一对多的情况)

javaType: 用来指定实体类中属性的类型。

ofType: 用来指定映射到List或集合中POJO的类型,泛型的约束类型。

Ⅰ 多对一查询:学生——老师

数据库表:

CREATE TABLE `teacher` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO teacher(`id`, `name`) VALUES (1, '王老师');

CREATE TABLE `student` (
`id` INT(10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;


INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

在这里插入图片描述

(1) 创建实体类POJO;
@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}
@Data
public class Teacher {
    private int id;
    private String name;
}

(2) 创建学生实体类对应的接口;
public interface StudentMapper {

    //查询所有学生的信息
    List<Student> getStudent();
    List<Student> getStudent2();
}
(3) 编写学生接口对应的Mapper.xml

为了达到和接口在同一个包中的效果,在resource文件夹下新建包结构com.glp.dao:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.glp.dao.StudentMapper">

<!--按照结果查询——联表查询-->
    <select id="getStudent2" resultMap="StudentMap2">
         select s.id sid,s.name sname,t.name tname from student s, teacher t where s.tid=t.id;
    </select>

    <resultMap id="StudentMap2" type="Student">
         <result property="id" column="sid"/>
         <result property="name" column="sname"/>

        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>


    <!--按照查询嵌套处理——子查询-->
        <select id="getStudent" resultMap="StudentMap" >
           select * from student;
        </select>

    <resultMap id="StudentMap" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂属性:对象association, 集合collection-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
        
        <select id="getTeacher" resultType="Teacher">
            select * from teacher where id = #{id};
        </select>

</mapper>

在多对一查询中,需要用到teacher这个表,每个学生都对应着一个老师。而property只能处理单个属性,像teacher这种复杂属性(内含多个属性)需要进行处理。处理复杂对象要用association

方式一:联表查询(直接查出所有信息,再对结果进行处理)

   <resultMap id="StudentMap2" type="Student">
         <result property="id" column="sid"/>
         <result property="name" column="sname"/>

        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

直接查询出学生和老师,然后用association去取老师里面的属性property。

方式二:子查询(先查出学生信息,再拿着学生中的tid,去查询老师的信息)

  <resultMap id="StudentMap" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂属性:对象association-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
        
        <select id="getTeacher" resultType="Teacher">
            select * from teacher where id = #{id};
        </select>

在resultMap中引入属性association,通过javaType指定property="teacher"的类型javaType="Teacher"。通过select引入子查询(嵌套查询)。
在这里插入图片描述
这里是拿到学生中的tid,去查找对应的老师。

(4)在核心配置类中引入Mapper

db.properties:数据库连接参数配置文件

driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&chracterEncoding=utf8
username =root
password =mysql

mybatis.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


    <properties resource="db.properties">
        <property name="username" value="root"/>
        <property name="password" value="mysql"/>
    </properties>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <typeAlias type="com.glp.POJO.Student" alias="Student"/>
        <typeAlias type="com.glp.POJO.Teacher" alias="Teacher"/>
    </typeAliases>


    <environments default="development">

        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>

    </environments>

    <mappers>
        <mapper class="com.glp.dao.StudentMapper"/>
        <mapper class="com.glp.dao.TeacherMapper"/>
    </mappers>

</configuration>

注意:
要保证接口和Mapper.xml都在同一个包中。

(5) 测试
public class UserDaoTest {
    @Test
    public void getStudent(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> list = mapper.getStudent();

        for (Student stu:list ) {
            System.out.println(stu);
        }
        sqlSession.close();
    }

    @Test
    public void getStudent2(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        List<Student> list = mapper.getStudent2();

        for (Student stu:list ) {
            System.out.println(stu);
        }
        sqlSession.close();
    }
}
Ⅱ 一对多查询:老师——学生

在这里插入图片描述

(1)实体类
@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}
(2) 接口
package com.glp.dao;

public interface TeacherMapper {

    Teacher getTeacher(@Param("tid") int id);

    Teacher getTeacher2(@Param("tid") int id);
}
(3)接口对应的Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="com.glp.dao.TeacherMapper">

  <!--方式一          =======================                  -->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname, t.id tid from
        student s ,teacher t where s.tid = t.id and t.id = #{tid};
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>


    <!--方式二          =======================                  -->

    <select id="getTeacher2" resultMap="TeacherStudent2">
        select * from teacher where id = #{tid};
         <!--这里的tid和接口中指定的属性名相同-->
    </select>

    <resultMap id="TeacherStudent2" type="Teacher">
	    <result property="id" column="id"/>
        <result property="name" column="name"/>
           <!--上面的两个可以省略-->
        <collection property="students"  column="id" javaType="ArrayList" ofType="Student"  select="getStuById"/>
    </resultMap>

    <select id="getStuById" resultType="Student">
        select * from student where tid=#{tid};
           <!--查询老师对应的学生,#{tid}-->
    </select>
</mapper>

方式一:联表查询,需要写复杂SQL
collection 用来处理集合,ofType用来指定集合中的约束类型
联合查询时,查询出所以结果,然后再解析结果中的属性,将属性property赋予到collection中。

方式二:子查询,需要写复杂映射关系

在这里插入图片描述
在这里插入图片描述
查询学生时,需要拿着老师的id去查找,column用来给出老师的id。

(4)测试:
package com.glp.dao;
public class UserDaoTest {

    @Test
    public void getTeacher(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

        Teacher teacher = mapper.getTeacher(1);

        System.out.println(teacher);

        sqlSession.close();
    }


    @Test
    public void getTeacher2(){
        SqlSession sqlSession = MyUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

        Teacher teacher = mapper.getTeacher2(1);

        System.out.println(teacher);

        sqlSession.close();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值