当前位置: 代码迷 >> 综合 >> Mybatis mapper XML 文件中使用 association 实现一对一关联
  详细解决方案

Mybatis mapper XML 文件中使用 association 实现一对一关联

热度:80   发布时间:2024-02-02 11:51:09.0

前言

  • Mybatis 一对一,使用 association 标签
  • Mybatis 一对多,使用 collection 标签
  • 本文主要说明 association 标签, collection 标签同理。
  • association 标签有两种用法:join查询、嵌套查询
  • 文中代码是从项目中Copy后再修改得到的,如果有对不上的地方,需要自动纠错。

假设,有下面这个实体类:

public class Car {/** 车辆编号 */private Long carid;/** 公司编号 */private Long comid;/** 车牌号 */private String carnum;/** 公司 */private Company company;...
}

association 的 join查询用法

略。

association 的嵌套查询用法

<?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.office.leasing.mapper.CarMapper"><resultMap type="Car" id="CarResult"><result property="carid"    column="carid"    /><result property="comid"    column="comid"    /><result property="carnum"    column="carnum"    /><result property="carbrand"    column="carbrand"    /><result property="carcolor"    column="carcolor"    /><result property="cartype"    column="cartype"    /><result property="remark"    column="remark"    /><result property="status"    column="status"    /><association property="company" javaType="Company" column="comid" select="selectCompany" /></resultMap><resultMap type="Company" id="CompanyResult"><result property="leaid"    column="leaid"    /><result property="leaname"    column="leaname"    /><result property="address"    column="address"    /><result property="telnumber"    column="telnumber"    /><result property="contacts"    column="contacts"    /><result property="createTime"    column="create_time"    /><result property="status"    column="status"    /></resultMap><select id="selectCarListCustom" parameterType="Car" resultMap="CarResult">select * from car<where>  <if test="carnum != null and carnum != ''"> and carnum = #{carnum}</if></where></select><select id="selectCompany" parameterType="Integer" resultMap="CompanyResult">select * from company where comid=#{comid}</select>
</mapper>
  • selectCompany#{comid}用的comid 对应数据库中car表的comid
  • #{comid}comid可以随便叫。比如可以用#{abc}替代#{comid}。因为parameterType="Integer",所以叫啥都无所谓了。

遇到符合主键是怎么办?

<resultMap type="XX" id="XXMap">         <id property="id" column="colid"/>  <id property="name" column="colname"/>  <collection property="list" javaType="ArrayList" column="{id = colid,name=colname}" select="getSubXXX"/>  </resultMap>
  • column="{id = colid,name=colname}" id+name为符合主键
  • id、name为别名
  • colid、colname为数据库中表的列名
  • getSubXXX中,直接使用别名即可,比如:#{id}

参考

https://www.cnblogs.com/YingYue/p/3912648.html

  相关解决方案