0
点赞
收藏
分享

微信扫一扫

mybatis根据id、idList查询数据

1、根据id查询:

mapper.xml中的sql语句如下:

<select id="getTestById" resultType="com.abc.Test" parameterType="int">  
select
<include refid="Base_Column_List" />
from test where id=#{id}
</select>

dao层接口代码:

Test getTestById(int id);

对于简单数据类型,sql映射语句中使用#{变量名}这种方式接收mapper接口方法传递过来的值。其实”变量名”可以是任意的,至于其叫什么名字其实是不可考也没必要知道的。(JAVA反射只能获取方法参数的类型,是无从得知方法参数的名字的)比如上面示例中使用#{id}来引用只是比较直观而已,使用其他名字来引用也是一样的。

:当传入参数是java对象类型,sql映射语句中就可以直接引用对象的属性名了(mybatis使用OGNL表达式),这里的属性名必须是真实的名字,不是可随意指定。

那么,当我们需要在sql语句中使用if标签判断传递的参数时,该如何写呢?在if元素中test传递的参数时,就必须要用_parameter来引用这个参数了。像这样:

<select id="getTestById" resultType="com.abc.Test" parameterType="int">  
select
<include refid="Base_Column_List" />
from test
<if test="_parameter != 0">
where id = #{id,jdbcType=INTEGER}
</if>
</select>

注意事项:

1)当id不存在时,返回的Test对象为null:

@Autowired
private TestDao testDao;
public void test() {

Test testObj = testDao.getTestById(1);//可能返回null
logger.info(testObj.toString());
}

2)当根据id查询出多个结果时,mybatis会报错:Expected one result (or null) to be returned by selectOne(), but found: 26

@Autowired
private TestDao testDao;
public void test() {

Test testObj = testDao.getTestById(0);//返回多个结果
logger.info(testObj.toString());
}

2、根据idList查询:

在SQL语法中如果我们想根据idlist查询是,可以使用in,例如:select * from HealthCoupon where useType in ( '4' , '3' )

但是如果在mybatis中的使用in的话,像如下去做的话,肯定会报错:(假设参数值:“4,3”)

<select id="selectByUserId" resultMap="BaseResultMap" parameterType="java.lang.String">
select * from HealthCoupon where useType in (#{useType,jdbcType=VARCHAR})
</select>

MyBatis中提供了foreach语句实现IN查询,foreach语法如下:

foreach语句中, collection属性的参数类型可以使:List、数组、map集合

  • collection: 必须跟mapper.java中@Param标签指定的元素名一样
  • item: 表示在迭代过程中每一个元素的别名,可以随便起名,但是必须跟元素中的#{}里面的名称一样。
  • index:表示在迭代过程中每次迭代到的位置(下标)
  • open:前缀, sql语句中集合都必须用小括号()括起来
  • close:后缀
  • separator:分隔符,表示迭代时每个元素之间以什么分隔

看个示例:

<select id="findByIdSet" resultMap="com.abc.Test" parameterType="java.util.List">  
select
<include refid="Base_Column_List" />
from test
where id in
<foreach collection="list" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</select>

dao层接口代码:

List<Test> findByIdSet(List<Integer> idList);

上例传入的是list,如果传入的是数组,collection属性要必须指定为 array,例如:

List<User> selectByIdSet(String[] idList);

<select id="selectByIdSet" resultMap="BaseResultMap">
SELECT
<include refid="Base_Column_List" />
from t_user
WHERE id IN
<foreach collection="array" item="id" index="index" open="(" close=")" separator=",">
#{id}
</foreach>
</select>

说明:对于返回list的数据,如果没有查到结果,不会返回null。

如果要传入多个参数,可以使用map,例如:

Map<String, Object> params = new HashMap<String, Object>(2);
params.put("name", name);
params.put("idList", ids);
mapper.selectByIdSet(params);

<select id="selectByIdSet" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user where
name = #{name}
and ID in
<foreach item="item" index="index" collection="idList" open="(" separator="," close=")">
#{item}
</foreach>
</select>

举报

相关推荐

0 条评论