当前位置: 代码迷 >> 综合 >> Mybatis-association
  详细解决方案

Mybatis-association

热度:67   发布时间:2023-12-02 08:43:22.0

以员工-部门为例子
在这里插入图片描述
1.第一种 使用方式
在EmployeeMapper.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smxy.maven.crud.dao.EmployeeMapper">
<!--  带部门的返回结果集--><resultMap id="WithDeptResultMap" type="com.smxy.maven.crud.pojo.Employee"><id column="emp_id" jdbcType="INTEGER" property="empId"/><result column="emp_name" jdbcType="VARCHAR" property="empName"/><result column="gender" jdbcType="CHAR" property="gender"/><result column="email" jdbcType="VARCHAR" property="email"/><result column="d_id" jdbcType="INTEGER" property="dId"/><association  property="department" javaType="com.smxy.maven.crud.pojo.Department"><id column="dep_id" property="depId" /><result column="dep_name" property="depName" /></association></resultMap><!--  带部门的sql片段--><sql id="WithDept_Column_List">tbl_emp.emp_id, tbl_emp.emp_name, tbl_emp.gender, tbl_emp.email, tbl_emp.d_id, tbl_dep.dep_id, tbl_dep.dep_name</sql><!--  带部门查询 selectByExampleWithDept(List)、selectByPrimaryKeyWithDept--><select id="selectByExampleWithDept" parameterType="com.smxy.maven.crud.pojo.EmployeeExample" resultMap="WithDeptResultMap">select<if test="distinct">distinct</if><include refid="WithDept_Column_List"/>from tbl_emp left join tbl_dep on tbl_emp.d_id = tbl_dep.dep_id<if test="_parameter != null"><include refid="Example_Where_Clause"/></if><if test="orderByClause != null">order by ${orderByClause}</if></select>
</mapper>

在这里插入图片描述
2.第二种方式

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.smxy.maven.crud.dao.EmployeeMapper"><!--  带部门的返回结果集--><resultMap id="WithDeptResultMap" type="com.smxy.maven.crud.pojo.Employee"><id column="emp_id" jdbcType="INTEGER" property="empId"/><result column="emp_name" jdbcType="VARCHAR" property="empName"/><result column="gender" jdbcType="CHAR" property="gender"/><result column="email" jdbcType="VARCHAR" property="email"/><result column="d_id" jdbcType="INTEGER" property="dId"/><association column="d_id" property="department" select="com.smxy.maven.crud.dao.DepartmentMapper.selectByPrimaryKey"></association></resultMap><sql id="Base_Column_List">emp_id, emp_name, gender, email, d_id</sql><!--  带部门查询 selectByExampleWithDept(List)、selectByPrimaryKeyWithDept--><select id="selectByExampleWithDept" parameterType="com.smxy.maven.crud.pojo.EmployeeExample" resultMap="WithDeptResultMap">select <include refid="Base_Column_List"/>from tbl_emp<if test="_parameter != null"><include refid="Example_Where_Clause"/></if><if test="orderByClause != null">order by ${orderByClause}</if></select>
</mapper>

在这里插入图片描述

  相关解决方案