【问题标题】:Can a query return only part of the results on a resultMap on Ibatis?Mybatis的resultMap上一个查询可以只返回部分结果吗?
【发布时间】:2014-07-10 18:57:02
【问题描述】:

有一些使用Ibatis 2.3的代码,我有一个类User和一个resultMap如下:

public class User {
  private Integer id;
  private String name;

  public Integer getId() {
    return this.id;
  }

  public void setId(final Integer id) {
    this.id = id;
  }

  public String getName() {
    return this.name;
  }

  public void setName(final String name) {
    this.name = name;
  }
}

<resultMap id="userResultMap" class="user">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
</resultMap>

然后我有一个只返回 id 的选择查询:

<select id="getUserId" resultMap="userResultMap">
    select id from Foo
</select>

像这样,Ibatis 想要在 resultMap 上填写所有结果,并且由于它发送的查询没有返回“name”并且错误:

--- The error occurred in ibatis/user.xml.  
--- The error occurred while applying a result map.  
--- Check the user.userResultMap.  
--- Check the result mapping for the 'name' property.  
--- Cause: java.sql.SQLException: Column 'name' not found.

是否有可能以某种方式让查询只返回 resultMap 上的部分结果?

【问题讨论】:

  • 不是mybatis这边的问题。检查您是否有名为“名称”的列
  • 查询没有返回“名称”列,这正是问题所在。我无法更改查询,它归其他人所有,实际上是对 Oracle 中的过程的调用。 Foo 不是一张桌子。查询看起来更像:'select id from app.getid() ...'
  • 那么你必须从resultmap中删除属性,因为mybatis找不到列'name'的表
  • 这正是我的问题,如果有办法在不同的 SQL 上重用相同的 ResultMap,但告诉 Ibatis 什么时候 SQL 不会返回其中一个列。当 SQL 上不存在列时,类似于“设置”该属性的默认值/空值。
  • 一种方法是使用继承。但在这种情况下,我看不到重用能力的真正优势。

标签: java mybatis ibatis ibatis.net


【解决方案1】:

您的选择查询应该是

<select id="getUserId" resultMap="userResultMap">
     select id, name from Foo
</select>

您的查询中缺少“名称”。 这很简单。您的结果图有两个属性,但您只选择了一个属性。应该完全一样。希望它有效。

【讨论】:

    【解决方案2】:

    如果是空白或空值,您可以在 sql 查询本身中为该 sql 列设置一些默认值,以便它始终返回带有值的该列。

    【讨论】:

      猜你喜欢
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      相关资源
      最近更新 更多