MyBatis-ResultMap处理映射关系 多对一和一对多

添加依赖

  <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.9</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
    </dependencies>

 添加日志输出

log4j.logger.com.chen=TRACE   com.chen 为自己包名 例如com.siwen

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.chen=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.rootLogger=DEBUG,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

 

1.jdbc配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/system?characterEncoding=UTF-8
jdbc.username=数据库账户
jdbc.password=密码

2.mybatis-config.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="jdbc.properties"></properties>
<!--    <settings>-->
<!--&lt;!&ndash;        将下划线映射为驼峰&ndash;&gt;-->
<!--        <setting name="mapUnderscoreToCameCase" value="true"/>-->
<!--    </settings>-->
    <typeAliases>
        <package name="com.chen.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>

    </environments>
    <mappers>
        <mapper resource="mapper/EmpMapper.xml"></mapper>
    </mappers>
</configuration>

3.实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Emp implements Serializable {
    private Integer emp_id;
    private String emp_name;
    private Integer age;
    private String gender;
    private Dept dept;
}


@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Serializable {
    private Integer dept_id;
    private String dept_name;
}

4.对应接口

public interface EmpDao {
    //分布查询
    //查询部门id
    Emp findById(@Param("emp_id") Integer emp_id);

    Dept findByDeptId(@Param("dept_id")Integer dept_id);
}

5.Mapper文件

ResultMap处理映射关系

<!--resultMap:设置自定义映射
id:映射的唯一标识
type:处理映射关系的实体类对象的类型
id:处理主键和实体类中属性的映射关系
column:设置映射关系字段名 必须是sql中查询出的字段名
property:设置映射关系属性的属性名 必须是实体类中的属性名
-->
    <resultMap id="RestultMapEmp" type="Emp">
        <id column="emp_id" property="emp_id"></id>
        <result column="emp_name" property="emp_name"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
    </resultMap>
    <select id="findById" resultMap="RestultMapEmp">
        select * from emp where emp_id=#{emp_id}
    </select>

1.处理多对一映射关系

1.1级联

    <resultMap id="RestultMapEmp" type="Emp">
        <id column="emp_id" property="emp_id"></id>
        <result column="emp_name" property="emp_name"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
        <result column="dept_id" property="dept.dept_id"></result>
        <result column="dept_name" property="dept.dept_name"></result>
    </resultMap>
    <select id="findById" resultMap="RestultMapEmp">
SELECT * from emp e LEFT JOIN dept d on e.dpet_id=d.dept_id
where e.emp_id=#{emp_id}
    </select>

1.2通过association

    <resultMap id="RestultMapEmp" type="Emp">
        <id column="emp_id" property="emp_id"></id>
        <result column="emp_name" property="emp_name"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
<!--        association:处理多对一的映射关系(处理实体类类型的属性)
            property:需要处理映射关系的属性名
            javaType:设置处理类型的属性-->
        <association property="dept" javaType="Dept">
            <id column="dpet_id" property="dept_id"></id>
            <result column="dept_name" property="dept_name"></result>
        </association>
    </resultMap>
    <select id="findById" resultMap="RestultMapEmp">
SELECT * from emp e LEFT JOIN dept d on e.dpet_id=d.dept_id
where e.emp_id=#{emp_id}
    </select>

1.3分布查询

    <resultMap id="RestultMapEmp" type="Emp">
        <id column="emp_id" property="emp_id"></id>
        <result column="emp_name" property="emp_name"></result>
        <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
<!--        property:设置需要处理映射关系的属性的属性名-->
<!--        select:设置分布查询的唯一标识-->
<!--        column:将查询的某个字段作为分布查询的字段sql-->
        <association property="dept"
                     select="com.chen.dao.EmpDao.findByDeptId"
                     column="dept_id">
        </association>
    </resultMap>
<!--    <select id="findById" resultMap="RestultMapEmp">-->
<!--SELECT * from emp e LEFT JOIN dept d on e.dpet_id=d.dept_id-->
<!--where e.emp_id=#{emp_id}-->
<!--    </select>-->
    <select id="findById" resultMap="RestultMapEmp">
        select * from emp where emp_id=#{emp_id}
    </select>
    <select id="findByDeptId" resultType="Dept">
        select * from dept where dept_id=#{dept_id}
    </select>

测试

public class EmpTest {
    public static SqlSessionFactory ssf=null;
    static {
        try {
            //读取配置文件
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //通过配置文件读取创建sql会话工厂
            ssf = new SqlSessionFactoryBuilder().build(is);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void findById(){
        SqlSession sqlSession = ssf.openSession(true);
        EmpDao mapper = sqlSession.getMapper(EmpDao.class);
        //Dept emp = mapper.findByDeptId(1);
        Emp emp = mapper.findById(1);
        System.out.println(emp);
    }
}

2.处理一对多映射关系 

这里通过查询一个部门下对应的员工为例子

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Serializable {
    private Integer dept_id;
    private String dept_name;
//一个部门下对应多个员工
    private List<Emp> emps;
}

collection   通过集合处理一对多的映射关系

方法一:联查

 1.部门接口中定义查询方法  通过查询获得部门id

Dept findDeptIdAndEmp(@Param("dept_id") Integer dept_id);

 2.通过多表联查

<resultMap id="ResultDept" type="Dept">
    <id column="dept_id" property="dept_name"></id>
    <result column="dept_name" property="dept_name"></result>
    <collection property="emps"
                select="com.chen.dao.EmpDao.findByEmp"
                column="dept_id"></collection>

<!--    ofType设置集合类型属性存储的数据的类型-->
    <collection property="emps" ofType="Emp">
        <id column="emp_id" property="emp_id"></id>
        <result column="emp_name" property="emp_name"></result>
       <result column="age" property="age"></result>
        <result column="gender" property="gender"></result>
   </collection>
</resultMap>
<select id="findDeptIdAndEmp" resultMap="ResultDept">
select * from dept  left JOIN emp  on dept.dept_id=emp.dept_id
where dept.dept_id=#{dept_id}
    </select>

方法二分布查询

先找部门id通过部门id找到对应员工信息

DeptMapper.xml

<resultMap id="ResultDept" type="Dept">
    <id column="dept_id" property="dept_name"></id>
    <result column="dept_name" property="dept_name"></result>
    <collection property="emps"
                select="com.chen.dao.EmpDao.findByEmp"
                column="dept_id"></collection>
</resultMap>

    <select id="findDeptIdAndEmp" resultMap="ResultDept">
        select * from dept where dept_id=#{dept_id}
    </select>
List<Emp> findByEmp(@Param("dept_id") Integer dept_id);

 EmpMapper.xml

    <select id="findByEmp" resultType="Emp">
        select * from emp where dept_id=#{dept_id}
    </select>

 测试

    @Test
    public void findDeptById(){
        SqlSession sqlSession = ssf.openSession(true);
        DeptDao mapper = sqlSession.getMapper(DeptDao.class);
        Dept dept = mapper.findDeptIdAndEmp(1);
        System.out.println(dept);
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: MybatisResultMap可以用来映射一对多关系。在ResultMap,可以使用collection标签来定义一个集合属性,用来表示一对多关系。在集合属性,可以使用result标签来定义子对象的映射规则。例如: <resultMap id="userMap" type="User"> <id property="id" column="id"/> <result property="name" column="name"/> <collection property="orders" ofType="Order"> <id property="id" column="order_id"/> <result property="name" column="order_name"/> </collection> </resultMap> 在上面的例子,User对象包含一个orders属性,用来表示一个用户可以有多个订单。使用collection标签来定义orders属性,并使用ofType属性来指定子对象的类型为Order。在集合属性,使用id和result标签来定义子对象的映射规则。这样,在查询结果,就可以将多个订单映射到一个User对象的orders属性。 ### 回答2: 在MyBatisResultMap是一种用于将查询到的结果集映射Java对象的机制。当查询结果集包含多个对象的属性时,就需要使用ResultMap一对多映射一对多映射的实现,需要在ResultMap定义一个collection元素来表示将多个对象映射成一个集合。collection元素需要设置property、ofType和select等属性。 property属性表示映射到结果集的查询条件,也就是查询多个对象时需要根据哪个属性进行关联。 ofType属性表示集合元素的类型,这里表示集合元素的类型为哪个Java类。 select属性表示查询的语句,对应于查询结果集的collection列。 例如,以下是一段使用ResultMap实现一对多映射的示例代码: <resultMap id="UserMap" type="User"> <id column="id" property="id"/> <result column="username" property="username"/> <result column="password" property="password"/> <collection property="books" ofType="Book" select="selectBooksByUser" column="id"/> </resultMap> 在上面的代码,UserMap是一个ResultMap配置,books是User类的一个List<Book>类型属性。通过collection元素的配置,表示User对象与多个Book对象之间存在一对多关系。 需要注意的是,以上的示例代码,还需要在mapper文件定义selectBooksByUser语句,用于查询对应的Book对象。同时,需要配置查询语句的查询条件,也就是column属性,与User对象的id属性关联起来。 通过以上的配置,如果查询结果集包含了User对象与多个Book对象,MyBatis就会根据配置进行自动映射,将查询结果集的数据转化为Java对象的形式,方便我们进行业务逻辑的处理。 ### 回答3: MyBatis是一种轻量级的ORM框架,支持复杂的SQL查询。其ResultMapMyBatis非常重要的一种映射规则,可以将查询结果映射Java对象。 在MyBatis,使用ResultMap进行一对多映射时,可以通过以下步骤完成: 1. 定义主实体类和从实体类 在一对多映射,主实体类代表一端,从实体类代表多端。例如,在一个学校的管理系统,Student代表主实体类,Grade代表从实体类。一名学生可以拥有多个成绩单。 2. 在主实体类增加从实体类的集合 在主实体类增加从实体类的集合属性,如下所示: public class Student { private int id; private String name; private List<Grade> grades; } 3. 定义ResultMap 定义ResultMap时,需要使用collection标签来映射从实体类的集合属性。注意,collection标签的属性property应该指向主实体类的集合属性,同时需要指定从实体类的ResultMap,如下所示: <resultMap id="studentResultMap" type="Student"> <id property="id" column="id"/> <result property="name" column="name"/> <collection property="grades" ofType="Grade" resultMap="gradeResultMap"/> </resultMap> 4. 定义从实体类的ResultMap 在从实体类的ResultMap,需要定义每一列的映射关系。同样地,需要定义id标签,指向主实体类的外键列,如下所示: <resultMap id="gradeResultMap" type="Grade"> <id property="id" column="id"/> <result property="subject" column="subject"/> <result property="score" column="score"/> <association property="student" javaType="Student"> <id property="id" column="student_id"/> <result property="name" column="student_name"/> </association> </resultMap> 5. 编写查询语句 最后,编写查询语句时,需要使用select标签,并在其指定ResultMap,如下所示: <select id="getStudent" resultMap="studentResultMap"> SELECT s.id, s.name, g.id, g.subject, g.score, g.student_id, s2.name as student_name FROM student s LEFT JOIN grade g on s.id = g.student_id LEFT JOIN student s2 on g.student_id = s2.id </select> 这样,就完成了从数据库查询学生及其所拥有的成绩单,并将结果映射为Student的对象。其,每个Student对象的grades属性是一个List,其包含多个Grade的对象。 以上就是使用ResultMap实现MyBatis一对多映射的步骤。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值