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

标签 java mybatis

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

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

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

Account 的 Mapper 接口(interface)很明显,映射文件包含选择

<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 分钟,这是 Not Acceptable 。

我希望将 resultMapcollection 一起使用会加快速度。但问题是如何 去做吧。 resultMap="account" 应该是什么样子

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

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

最佳答案

如果你使用下面的resultmap

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

关于java - 映射集合 ('select *' ) 到 MyBatis 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7913343/

相关文章:

java - 如何给 JTable 单元格边框(左、右、上、下)不同的颜色?

java - 为什么接口(interface)和xml映射器文件必须在同一个包中并具有相同的名称?

java - MyBatis:如何返回列表映射?

java - 使用 Java 的 MyBatis 生成器无法正常工作

Java:构建器模式与逻辑分组对象

java - 是否可以实现一个带有 <Generic extends X> 类型参数的类?

Java URLConnection 响应已编码

java - CXF 无 Spring

spring - 上下文 :property-placeholder doesn't resolve references

mysql - MyBatis Spring 集成 - POJO 上未设置某些 ResultSet 值