【问题标题】:Mapping collection ('select *') to field in MyBatis将集合('select *')映射到 MyBatis 中的字段
【发布时间】:2011-10-27 08:21:13
【问题描述】:

我被堆叠了。我想直接使用 sql 代替 mybatis faramework。 我想选择具有填充属性映射的帐户列表。

但是让我们从头开始,第一个 Account 类

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

Account 的映射器接口很明显,映射文件包含选择

<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>

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

【问题讨论】:

    标签: java mybatis


    【解决方案1】:

    如果你使用下面的结果图

    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-17
      • 2012-10-13
      • 2021-12-09
      • 2013-07-27
      • 2014-10-11
      • 2012-11-18
      • 1970-01-01
      • 2015-07-13
      相关资源
      最近更新 更多