概述:mybatis/mybatis-plus 子查询实现 涉及到in、exist操作
在开发时候,经常会用到涉及到in exist 等子查询。
myabtis
①以注解的方式进行操作
@Select("select column_1 from table_name where column_2 in (${column_parms}) ") public List<String> getNames(@Parms("column_parms") String column_parms) @Select("select column_1 from table_name <where> <if test =\"column_parms!=null and column_parms.size()\"> column_2 in <foreach collcetion=\"column_parms\" item=\"item\" index=\"index\" open=\"(\" separator = \",\" close=\")\"> #{item} </foreach> </if> </where> public List<String> getNames(@Parms("column_parms") List<String> column_parms)
②以xml方式
mapper.xml文件
<select id="getNames" resultType="String"> select column_1 from table_name where column_2 in (${column_parms}) <select id="getNames" resultType="String"> select column_1 from table_name <where> <if test ="column_parms!=null and column_parms.size()"> column_2 in <foreach collcetion="column_parms" item="item" index="index" open="(" separator = "," close=")"> #{item} </foreach> </if> </where>
IService 文件
List<String> getNames(@Param("column_parms") String column_parms) List<String> getNames(@Param("column_parms")List<String> column_parms)
仔细观察上面代码,只有两个地方是不同的:
${}取值 String参数 ${} 这种是取值以后再去编译SQL语句
#{}取值 List参数 #{} 这种取值是编译好SQL语句再取值
但是如果在in里面又涉及到子查询,那么只能用${}取值
eg:select column_1 from table_name1 where column_2 in
( select column_3 from table_name2 where column_4 in(result集合) )
这种的话是无法使用foreach 进行操作的 ,因为对table_name1 表的in操作 字段属性 这个参数是无法取到的,因此在执行的会报空值针异常错误。
正确的写法:
@Delete("DELETE FROM HJ_GG_HXY_QXGXB WHERE HQXGXB_HYID IN " + "( SELECT HJSGXB_HYID FROM GG_HXY_JSGXB WHERE HJSGXB_HXID " + " IN (${ids}) " + ")") void del(@Param("ids") String ids);