mybatis的foreach、if、choose when使用

package org.sjframework.learn.mybatis.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

/**
 * mybatis dao
 * <p>
 * note:order by need use ${}
 *
 * @author 719383495@qq.com | 719383495qq@gmail.com | 有问题可以邮箱或者github联系我
 * @date 2019/10/14 22:10
 */
@Mapper
public interface UserDao {

    /**
     * get
     *
     * @param param
     * @return
     */
    @Select("select * from t_user where user_id = #{?}")
    List<Map<String, String>> get(String param);

    /**
     * test01 list or array
     * <p>
     * collection default list/array if not @Param
     *
     * @param param
     * @return
     */
    @Select("<script>select * from t_user where user_id in " +
            "<foreach collection=\"list0\" index=\"index\" item=\"item\" open=\"(\" separator=\",\" close=\")\">" +
            "#{item}</foreach></script>")
    List<Map<String, String>> test01(@Param("list0") List param);

    /**
     * test02 map
     *
     * @param param
     * @return
     */
    @Select("<script>select * from t_user where user_id in " +
            "<foreach collection=\"ids\" index=\"index\" item=\"item\" open=\"(\" separator=\",\" close=\")\">" +
            "#{item}</foreach></script>")
    List<Map<String, String>> test02(Map param);

    /**
     * test03 list<Map>
     *
     * @param param
     * @return
     */
    @Select("<script>select * from t_user where user_id in " +
            "<foreach collection=\"list\" index=\"index\" item=\"item\" open=\"(\" separator=\",\" close=\")\">" +
            "#{item.id}</foreach></script>")
    List<Map<String, String>> test03(List<Map> param);


    /**
     * test04
     * if
     *
     * @param param
     * @return
     */
    @Select("<script>select * from t_user where 1=1 " +
            "<if test=\"uid!=null and uid!=''\">and user_id = #{uid}</if>" +
            "<if test=\"uid==null or uid==''\">and user_id ='U00002'</if>" +
            "</script>")
    List<Map<String, String>> test04(@Param("uid") String param);

    /**
     * test05
     * choose when otherwise like switch
     *
     * @param param
     * @param sort
     * @return
     */
    @Select("<script>select * from t_user where 1=1 " +
            "<choose>" +
            "<when test=\"uid!=null and uid!=''\">and user_id = #{uid}</when>" +
//            "<when test=\"uid!=null and uid!=''\">and user_id = 'U00003'</when>" +
            "<otherwise>and user_id in ('U00002','U00003')</otherwise></choose>" +
            "order by user_id ${sort}" +
            "</script>")
    List<Map<String, String>> test05(@Param("uid") String param, @Param("sort") String sort);

}
``

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励