mybatis: foreach实现in集合查询(mybatis 3.5.7)
一,示例代码:
1,OrderController.java
List<Cart> cartList = cartService.getAllCartByCartId(userId,cartIds,configBeanValue.goodsImagesHost,configBeanValue.attrHost);
2,CartServiceImpl.java
@Override public List<Cart> getAllCartByCartId(Long userId,Long[] cartIds,String urlHost,String urlHostAttr) { //List<Cart> listCart = cartMapper.selectAllCartByUserId(userId); List<Cart> listCart = cartMapper.selectAllCartByCartId(userId,cartIds); ...
3,CartMapper.java
List<Cart> selectAllCartByCartId(@Param("userId")Long userId, @Param("cartIds")Long[] cartIds);
4,CartMapper.xml
<select id="selectAllCartByCartId" resultType="com.yj.storeback.pojo.Cart"> select c.* from cart as c,goods as g where c.userId=#{userId} and c.goodsId=g.goodsId and g.isSale=1 and c.cartId IN <foreach collection="cartIds" item="id" index="index" open="(" close=")" separator=","> #{id} </foreach> order by c.cartId desc </select>
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
本文: https://blog.imgtouch.com/index.php/2023/06/01/mybatis-foreach-shi-xian-in-ji-he-cha-xun-mybatis-3-5-7/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,测试效果
查看sql查询的日志:
Creating a new SqlSession SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cd7fbe6] was not registered for synchronization because synchronization is not active JDBC Connection [HikariProxyConnection@1874055310 wrapping com.mysql.cj.jdbc.ConnectionImpl@6052b4a0] will not be managed by Spring ==> Preparing: select c.* from cart as c,goods as g where c.userId=? and c.goodsId=g.goodsId and g.isSale=1 and c.cartId IN ( ? , ? ) order by c.cartId desc ==> Parameters: 1(Long), 25(Long), 24(Long) <== Columns: cartId, isDirect, userId, goodsId, skuId, goodsName, skuAttrNames, skuAttrIds, price, amount, addTime, isCheck, packType, addFrom <== Row: 25, 0, 1, 1, 22, 元気森林苏打水气泡水无糖饮料元气水, 480ml, 58, 44.00, 4, 2022-02-25 17:15:12, 1, 2, wap <== Row: 24, 0, 1, 2, 1, 张裕 第九代特选级解百纳7, dd_22, 2_4, 8.00, 4, 2022-02-24 19:01:29, 1, 2, wap <== Total: 2 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cd7fbe6]
前端效果:
三,查看mybatis的版本: