前言
记录一下自定义mybatis *.xml的用法,建立在已经mybatis generator反向生成了mapper.xml文件
1. 一对一
代码如下(示例):
/**
* 返回model结构,packageDto嵌套productDto,关联字段product_id
*/
@Data
public class SearchModel extends PackageDto {
private ProductDto productDto;
}
<?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文件
<mapper namespace="com.example.demo.base.custom.mapper.SearchPackageMapper">
// id:对应主查询resultMap名,type:返回model,extends:对继承类packageDto做字段对应
<resultMap id="BaseResultMap" type="com.example.demo.base.custom.condition.SearchModel" extends="com.example.demo.base.mapper.PackageMapper.BaseResultMap">
// property:对应返回model属性,select:自定义查询id, column:两个表关联
<association property="productDto" select="selectProductDto" column="product_id"/>
</resultMap>
// 主查询sql
<select id="searchPackageList" resultMap="BaseResultMap">
SELECT
*
FROM
package
WHERE
package_id = #{searchPackageDto.packageId}
</select>
// resultMap:对自定义查询的productDto做字段对应
<select id="selectProductDto" resultMap="com.example.demo.base.mapper.ProductMapper.BaseResultMap">
// 根据关联字段查询productDto数据
SELECT
*
FROM
product
WHERE
product_id = #{product_id}
</select>
</mapper>
2. 一对多
代码如下(示例):
// product和package是一对多关系,关联字段product_id
@Data
public class SearchPackageModel extends ProductDto {
private List<PackageDto> packageDtos;
}
<mapper namespace="com.example.demo.base.custom.mapper.SearchPackageMapper">
<resultMap id="BaseResultMap" type="com.example.demo.base.custom.condition.SearchPackageModel" extends="com.example.demo.base.mapper.ProductMapper.BaseResultMap">
// 查询packageDto是list,所以使用标签<collection>,关联字段product_id
<collection property="packageDtos" select="selectPackageDtoList" column="product_id"/>
</resultMap>
<select id="searchPackageList" resultMap="BaseResultMap">
SELECT
*
FROM
product
WHERE
product_id = '69fc6c86-7985-405e-ba25-457aead57f66'
</select>
<select id="selectPackageDtoList" resultMap="com.example.demo.base.mapper.PackageMapper.BaseResultMap">
SELECT
*
FROM
package
WHERE
product_id = #{product_id}
</select>
</mapper>
记录遇到的问题:
1.特殊字符转义问题
模糊查询问题
1)LIKE CONCAT(’%’,代码,’%’)
2)LIKE “%“代码”%”
对于多字段关联