您可以尝试将类型添加到结果列并配置 @TypeDiscriminator 以向 mybatis 提供要实例化哪个类的提示:
@Select("SELECT t.*, ${type} as type_discriminator" +
" FROM ${type} as t " +
" WHERE objectId >= ${start} AND objectId <= ${end}")
@TypeDiscriminator(column = "type_discriminator",
cases = {
@Case (value="SomeContentProviderBeanSubclass",
type=SomeContentProviderBeanSubclass.class,
results={
@Result(property="someField", column="some_field"),
// other columns mapping
}),
@Case (value="OtherContentProviderBeanSubclass",
type=OtherContentProviderBeanSubclass.class,
results={
@Result(property="otherField", column="other_field"),
}),
// @Cases for other ContentProviderBean subclasses
})
ArrayList<? extends ContentProviderBean> getFeed(@Param("type") String type,
@Param("start") int start, @Param("end") int end);
请注意,Case 中的 value 属性应与 getFeed 的类型参数匹配。
您可能会遇到几个陷阱:
- 需要为多种类型复制结果字段映射
- 使用mybatis注解时无法使用自动列映射
您可以尝试通过使用 xml 映射配置来克服这些问题。它可能看起来像:
<resultMap id="resultContentProviderBean"
type="ContentProviderBean"
autoMapping="true">
<id property="id" column="id"/>
<discriminator javaType="string" column="employee_type">
<case value="SomeContentProviderBeanSubclass"
resultType="SomeContentProviderBeanSubclass"
autoMapping="true"/>
<case value="OtherContentProviderBeanSubclass"
resultType="OtherContentProviderBeanSubclass"
autoMapping="true"/>
</discriminator>
</resultMap>
<select id="getFeed" resultMap="resultContentProviderBean">
SELECT t.*, ${type} as type_discriminator
FROM ${type} as t
WHERE objectId >= ${start} AND objectId <= ${end}
</select>