【问题标题】:How to nest one-to-many queries in one-to-one nested queries in MybatisMybatis中一对一嵌套查询如何嵌套一对多查询
【发布时间】:2018-07-01 13:41:41
【问题描述】:

这是我的 SQL 和 resultmap:

 <resultMap id="playerMap" type="player">
    <id column="playerId" property="id"/>
    <result column="playerName" property="name"/>
    <association property="team" javaType="Team">
        <id column="teamId" property="id"/>
        <result column="teamName" property="name"/>
    </association>
</resultMap>
<select id="selectPlayerById" resultMap="playerMap">
    select p.id playerId,p.name playerName,
    t.name teamName,t.id teamId
    from t_player p,t_team t
    where p.tid=t.id and p.id=#{id}
</select>

这是我的结果:

但“玩家”一栏为空。如何更改我的 SQL 语句,以便该列可以查询多个玩家的信息?

【问题讨论】:

    标签: java sql mybatis


    【解决方案1】:

    首先,你必须弄清楚,你想代表什么样的关系。

    对我来说,看起来你有一个类玩家和一个成员玩家。那么,玩家可以拥有玩家吗?

    如果您想选择所有或多个玩家,您必须添加第二个select-元素或将现有的更改为类似的内容:

    <select id="selectPlayers" resultMap="playerMap">
        select p.id playerId,p.name playerName,
        t.name teamName,t.id teamId
        from t_player p,t_team t
        where p.tid=t.id
    </select>
    

    您可以根据需要扩展 where 子句。

    如果你使用interfaces访问mybatis-xml-mappers中的方法,你必须在具体的interface中添加如下方法:

    List<Player> selectPlayers();
    

    我们也可以将两个选择组合成类似的东西:

    mapper-xml 中只有一个select-元素

    <select id="selectPlayers" resultMap="playerMap">
        select p.id playerId,p.name playerName,
        t.name teamName,t.id teamId
        from t_player p,t_team t
        where p.tid=t.id
        <choose>
            <when test="id != null" >
                and p.id=#{id}
            </when>
            <when test="name != null" >
                and p.name=#{name}
            </when>
            <otherwise>
    
            </otherwise>
        </choose>
    </select>
    

    有一个对应的interface-方法:

    List<Player> selectPlayers(@Param("id") long id, @Param("name") String name);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 1970-01-01
      • 2017-06-23
      • 2022-11-24
      • 2021-10-02
      相关资源
      最近更新 更多