将集合('select *')映射到MyBatis中的字段

时间:2011-10-27 08:21:13

标签: java mybatis

我堆积如山。我想替换直接使用sql而使用mybatis faramework 。 我想选择填充属性映射的帐户列表。

但是让我们从头开始,首先是Account类

public class Account {
     private int id;
     ...
     private Map<String, String> properties;
     ...
     //setters / getters
}

帐户的Mapper界面很明显,映射文件包含选择

<select id="getAccountById" resultMap="account">
       select ... from account where id = #{id}
</select>

<select id="getAccountProperties" resultType=map>
       select * from properties where id=#{id}
</select>

第一个选择返回Account对象,第二个java.util.Map包含列名 / 对。

我希望每个帐户对象都包含带有属性的地图,因此我会迭代帐户列表并按ID选择其属性

for(Account account : accountList) {
    int id = account.getId();
    Map properites = mapper.getAccountProperties(id);
    account.setProperties(properties);
}

基本上它可行,但对于200个帐户大约需要2分钟,这是不可接受的。

我希望resultMapcollection一起使用会加快速度。但问题是如何 去做吧。 resultMap="account"应如何看待

<resultMap id="account" type="Account">
   <id property="id" column="id">
   ...
   <collection property="properties" javaType="map" column="id" select="getAccountProperties" />
</resultMap>

在这种情况下,所选帐户对象不包含任何属性。 最大的问题是:如何将属性与帐户对象相关联?

1 个答案:

答案 0 :(得分:3)

如果您使用以下结果图

<resultMap id="account" type="Account">
    <result property="id" column="id">
    <result property="properties" column="id" select="getAccountProperties" />
</resultMap>

然后,对于每个帐户,MyBatis执行getAccountProperties语句,将列id的值作为参数传递,但您必须允许在select标记中接受它:

<select id="getAccountProperties" resultClass="java.util.Map" parameterClass="java.lang.Integer" >
    select * from properties where id=#value#
</select>
相关问题