注意事项:
(1)内部类必须是静态内部类。
(2)xml
中内部类连接使用$
。
下面看一个示例。
JavaBean 代码:
java
import lombok.Data;
import java.util.List;
/**
* @author wangbo
* @date 2019/9/30 9:26
*/
@Data
public class LeaveMessageQueryCondition {
private Integer projectId;
private String projectName;
private List<CustomQuestion> questions;
private List<CustomOrganization> organizations;
@Data
public static class CustomQuestion {
private Integer questionId;
private String questionName;
}
@Data
public static class CustomOrganization {
private Integer channelId;
private Integer organizationId;
private String organizationName;
}
}
如果LeaveMessageQueryCondition
类里面的内部类CustomQuestion
和CustomOrganization
没有使用static
修饰,MyBatis
在将查询结果封装到返回类型的时候会报没有匹配的构造器错误:
java
org.mybatis.spring.MyBatisSystemException:
nested exception is org.apache.ibatis.executor.ExecutorException:
No constructor found in cn.wangbo.model.survey.LeaveMessageQueryCondition$CustomQuestion matching
[java.lang.Long, java.lang.String, java.lang.Long, java.lang.String, java.lang.Long, java.lang.Long, java.lang.String]
原因是非静态内部类需要依赖外部类实例,异常提示可以看出,外部类的构造器参数包括了所有非静态内部类的属性。
resultMap 代码:
xml
<resultMap id="queryConditionResult" type="cn.wangbo.model.survey.LeaveMessageQueryCondition">
<result property="projectId" column="project_id" />
<result property="projectName" column="project_name" />
<collection property="questions" ofType="cn.wangbo.model.survey.LeaveMessageQueryCondition$CustomQuestion">
<result property="questionId" column="question_id" />
<result property="questionName" column="question_name" />
</collection>
<collection property="organizations" ofType="cn.wangbo.model.survey.LeaveMessageQueryCondition$CustomOrganization">
<result property="channelId" column="channel_id" />
<result property="organizationId" column="organization_id" />
<result property="organizationName" column="organization_name" />
</collection>
</resultMap>
这里注意内部类和外部类的连接符号不同于Java
中的点.
。必须使用$
连接符,否则在项目启动的时候会报类找不到异常。
java
java.lang.ClassNotFoundException:
Cannot find class:
cn.wangbo.model.survey.LeaveMessageQueryCondition.CustomQuestion
查询 SQL 代码:
xml
<select id="getLeaveMessageQueryCondition" resultMap="queryConditionResult">
SELECT project_id, project_name, question_id, question_name, channel_id, organization_id, organization_name
FROM ...
LEFT JOIN ... ON ...
LEFT JOIN ... ON ...
WHERE ...
</select>
查询返回结果:
json
{
"code": 200,
"message": "OK",
"data": [{
"projectId": 77789,
"projectName": "测试",
"questions": [{
"questionId": 222,
"questionName": "输入框类"
}],
"organizations": [{
"channelId": 111,
"organizationId": 555,
"organizationName": "测试系统公司"
}]
}]
}