MyBatis TooManyResultsException 看似正确的映射

MyBatis TooManyResultsException for seemingly correct mapping

为了解决这个问题,我减少了很多代码。

当我尝试不同的方法来使这个集合正常工作时,我继续收到此错误:

nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2

相关对象如下:

class Recipe {
    String name
    List<RecipeIngredient> ingredients
}
class RecipeIngredient {
    Double measurementAmount
}

我的方法调用有一个接口:

public interface CookbookDao {
    public Recipe getRecipe(@Param("id")int id)
}

我的结果映射器:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cookbook.daos.CookbookDao">
    <select id="getRecipe" resultMap="Recipe">
        SELECT
          r.name,
          ri.measurement_amount
        FROM
          recipe r
          INNER JOIN recipe_ingredient ri on ri.recipe_id = r.id
        WHERE
          r.id = #{id}
    </select>

    <resultMap id="Recipe" type="cookbook.domain.Recipe">
        <result property="name" column="r.name" />
        <collection property="ingredients" ofType="cookbook.domain.RecipeIngredient">
            <result property="measurementAmount" column="ri.measurement_amount"/>
        </collection>
    </resultMap>
</mapper>

查询 returns 以下结果(注意:虽然上面的代码只有 "measurement_amount",但我已经包含了实际的最终结果集,以帮助说明为什么我 want/need 返回这两行):

 name | measurement_amount | name | abbreviation | name  
------+--------------------+------+--------------+-------
 Rice |                  1 | cup  |              | rice
 Rice |                  2 | cups |              | water

当我取出集合时,我可以让映射器工作。 我试过使用 javaType,也试过在集合中使用复合键,但它仍然没有用。我有 运行 个想法并查看了大量帮助帖子,但没有什么特别突出的。

我正在使用 Spring Boot with UTD versions of mybatis and mybatis-spring

事实证明,MyBatis 不理解我与别名表的关联,所以我将查询更改为:

SELECT
  r.name as recipe_name,
  ri.measurement_amount as measurement_amount
FROM
  recipe r
  INNER JOIN recipe_ingredient ri on ri.recipe_id = r.id
WHERE
  r.id = #{id}

并更新映射器以使用列的别名(recipe_name 而不是 ri.name,等等),例如:

<resultMap id="Recipe" type="cookbook.domain.Recipe">
    <result property="name" column="recipe_name" />
    <collection property="ingredients" ofType="cookbook.domain.RecipeIngredient">
        <result property="measurementAmount" column="measurement_amount"/>
    </collection>
</resultMap>

成功了!

感谢评论帮助的人

你可以尝试使用 List.

public interface CookbookDao {
    public List<Recipe> getRecipe(@Param("id")int id);
}