如何动态选择一个resultMap并将一个递增的整数值附加到MyBatis中的“不存在”列中?

时间:2019-06-06 06:28:41

标签: java mybatis

我在使用角色和相关表的sakila数据库的MYSQL数据库中有一个特定的结果集:

actor_id first_name last_name title
1        PENELOPE   GUINESS   ANACONDA CONFESSIONS
1        PENELOPE   GUINESS   ANGELS LIFE

我已经使用以下结果映射图在MyBatis Plus中成功映射了以下数据:

    <resultMap id="actor" type="java.util.TreeMap">    
            <result property="id"       column="id" />      
            <result property="firstname"        column="first_name"  />   
            <result property="lastname"         column="last_name"  /> 
           <collection property="movies" javaType="ArrayList" resultMap="movies" />    
    </resultMap>

 <resultMap id="movies" type="java.util.TreeMap">
        <result property="title"    column="title" />      
    </resultMap>

SQL查询如下:

<select id="getActors" parameterType="ActorDetailsDTO" resultMap="actor">
select 
    a.actor_id,
    first_name,
    last_name,
    title
from actor a left join
film_actor fa on a.actor_id = fa.actor_id left join
film f on fa.film_id = f.film_id
where a.actor_id = #{id}
</select>

这又实现了以下结果:

result :{
    "id" : 1,
    "movies":[
      {
          title : "ANACONDA CONFESSIONS"          
      },
      {
          title : "ANGELS LIFE"          
      },
    ],
    "firstname" : "PENELOPE",
    "lastname"  : "GUINESS"
 }

但是我发现很难添加一个“不存在的”列名“ movielist”,其值为“ blockbuster X”,其中X是从1到N的递增数字。

我希望达到这个结果:

  result :{
        "id" : 1,
        "movies":[
          {
              "movielist" : "blockbuster 1",
              "title" : "ANACONDA CONFESSIONS"          
          },
          {
              "movielist" : "blockbuster 2",
              "title" : "ANGELS LIFE"          
          },
        ],
        "firstname" : "PENELOPE",
        "lastname"  : "GUINESS"
     }

当然,如果我有两个或两个以上的演员,“重磅炸弹X”将回到第二个演员的1。

我在SQL查询中所做的是添加一个变量计数器,但是该计数只是继续计数,而不是为新的参与者重置。

感谢您能提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

应该可以使用变量,但这是使用子查询的另一种方法。

<select id="getActors" resultMap="actor">
  select
    a.actor_id,
    first_name,
    last_name,
    fa.film_id,
    concat('blockbuster ', (select count(*) from film_actor fa2
      where a.actor_id = fa2.actor_id and fa2.film_id <= fa.film_id)) movielist,
    title
  from actor a
  left join film_actor fa on a.actor_id = fa.actor_id
  left join film f on fa.film_id = f.film_id
  order by a.actor_id, fa.film_id;
</select>

这是结果图。
添加了<id />元素以提高效率。

<resultMap id="actor" type="java.util.TreeMap">
  <id property="id" column="actor_id" />
  <result property="firstname" column="first_name" />
  <result property="lastname" column="last_name" />
  <collection property="movies" javaType="list"
    resultMap="movies" />
</resultMap>

<resultMap id="movies" type="java.util.TreeMap">
  <id column="film_id" /><!-- not stored in map -->
  <result property="movielist" column="movielist"
    javaType="string" /><!-- CONCAT returns VARBINARY -->
  <result property="title" column="title" />
</resultMap>