mybatis-plus 关联查询
其他
2020-04-12 13:57:01
阅读次数: 0
一、mybatis-plus的关联查询
- 前面讲到mybatis-plus生成代码,实体类继承基类
- 这次,聊下关于mybatis-plus 关联查询的问题。在自动生成的controller,entity,service,mapper,xml只能满足单表查询。如果要进行多表关联查询,就要改动xml来实现了。
- 假设有实体类CabinetInfo 和 CityAddressInfo,CabinetInfo存在addressId 与 CityAddressInfo 的id 对应。已知CabinetInfo的addressId,现在要查询出addressId对应的城市名称,放到cabinetinfo里面。
- 实体类CainetInfo:
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class CabinetInfo extends BaseEntity {
private static final long serialVersionUID=1L;
private String cabinetName;
private String cabinetCode;
private Integer addressId;
@TableField(exist=false)
private CityAddressInfo cityAddressInfo;
}
- 如上,在CabinetInfo里添加CityAddressInfo,并添加注解@TableField,设置该实体非CabinetInfo的数据库字段。
- 在CabinetInfoMapper.xml 中加入resultMap:
<resultMap id="CabinetInfo" type="com.location.entity.CabinetInfo">
<result column="id" property="id" />
<result column="cabinet_name" property="cabinetName" />
<result column="cabinet_code" property="cabinetCode" />
<result column="address_id" property="addressId" />
<result column="update_id" property="updateId" />
<result column="update_time" property="updateTime" />
<result column="create_id" property="createId" />
<result column="create_time" property="createTime" />
<association property="cityAddressInfo" javaType="com.location.entity.CityAddressInfo">
<id column="id" property="id"/>
<result column="address_name" property="addressName" />
<!--如有其他字段需要,自行添加-->
</association>
</resultMap>
- 现在本diao要查询CabinetInfo,并且把对应的addressName查询出来:
<select id="selectCabinetAndAddressName" resultMap="CabinetInfo">
SELECT ci.id,ci.cabinet_name,cai.id,cai.address_name
FROM cabinet_info ci left join city_address_info cai
ON ci.address_id = cai.id
WHERE 1 = 1
</select>
- 以上!!!果然相比JOOQ,还是中意mybatis。
发布了40 篇原创文章 ·
获赞 26 ·
访问量 4万+
转载自blog.csdn.net/guowujun321/article/details/103302843