【发布时间】:2015-09-25 02:03:03
【问题描述】:
我不知道如何使用 mybatis 结果生成一个复杂的对象。
我有以下映射器类:
public interface StationMapper {
@MapKey("stationId")
Map<Integer,Station> getStations();
}
由以下 resultMap 构建:
<resultMap id="stationMap" type="Station">
<result column="station_id" property="stationId" />
<result column="another_id" property="notUniqueId" />
<result column="name" property="name" />
</resultMap>
我希望 getStations() 的返回类型不是地图,而是一个将地图(或集合)作为构造函数的对象,以便我可以在对象构造上执行一些代码。
public class FancyStationMapHolder {
public FancyStationMapHolder(Map<Integer,Station> stations) {
executeSpecialCode(stations);
}
// OR
public FancyStationMapHolder(Collection<Station> stations) {
executeSpecialCode(stations);
}
}
public interface StationMapper {
FancyStationMapHolder getStations();
}
我认为我不能使用
或者,我想要一个带有此签名的 StationMapper 方法:
@MapKey("notUniqueId")
Map<String,Collection<Station>> getStationsByNotUniqueId();
编辑: 如果我基于某些列限制它并设置属性而不是使用构造函数,我可以获得这个复杂的对象,但是如果没有关系限制,我怎么能做到呢?
<resultMap id="fancyMap" type="sample.FancyStationMapHolder">
<result column="someId" property="someId"/>
<collection property="stations" column="someId" resultMap="stationMap"
select="stations" javaType="ArrayList" />
</resultMap>
我更喜欢使用构造函数,所以我也很感激这方面的建议。以下设置会导致此异常:
org.mybatis.spring.MyBatisSystemException:
nested exception is org.apache.ibatis.reflection.ReflectionException:
Error instantiating class sample.FancyStationMapHolder with invalid types
(ArrayList,) or values ([...
<resultMap id="fancyMap" type="sample.FancyStationMapHolder">
<constructor>
<arg column="someId" resultMap="stationMap" select="stations"
javaType="ArrayList" />
</constructor>
<result column="someId" property="someId"/>
</resultMap>
【问题讨论】: