本帖采用测试类进行测试 省略了controller层和service层 动态SQL在后边直接下翻
1.查询id为2-4的数据(包含2和4) 传参方式采用map传递
mapper层: 本帖采用测试类进行测试 省略了controller层和service层
@Test
void contextLoadsId() {
HashMap<String,Integer> map = new HashMap<>();
map.put("minId", 2);
map.put("maxId", 4);
List<User> users=userMapper.selectById(map);
System.out.println(users);
}
mapper接口:
List<User> selectById(HashMap<String, Integer> map);
xml文件查询sql:
<select id="selectById" resultType="com.jt.pojo.User">
select * from user where id >= #{minId} and id <= #{maxId}
</select>
其中#{minId} #{maxId} 对应的是 map中的key < 为 转义符 ( < : 小于 > : 大于)
2.由于mybatis只支持单值传参 多值传参是使用 @Param注解 代码如下
@Test
void contextLoadsId2() {
Integer minId = 1;
Integer maxId = 5;
List<User> users=userMapper.selectById2(minId,maxId);
System.out.println(users);
}
mapper接口:
List<User> selectById2(@Param("minId") Integer minId, @Param("maxId")Integer maxId);
xml文件查询sql:
<select id="selectById2" resultType="com.jt.pojo.User"> <![CDATA[ select * from user where id >= #{minId} and id <= #{maxId} ]]> </select>
其中<![CDATA["sql语句"]]>为万能转义符 当需要转移字符过多时 采用万能转义符,实际上此注解本质上也是将参数封装成map传递
3批量查询 id为2和4的数据 为了演示方便所以只查询2,4的数据(我承认我懒了)
@Test
void contextLoadsId5() {
Integer[] in ={2,4};
List<User> users=userMapper.selectByIn(in);
System.out.println(users);
}
mapper接口:
List<User> selectByIn(Integer[] in);
xml文件查询sql:
<!--
关于Mybatis的遍历的写法
foreach:
1. collection 需要遍历的集合
1.1 数组 关键字: array/list
1.2 list集合 关键字: list/array
1.3 Map<key,array/list> 关键字:key
2. open/close 循环体的开始和结束 可以写到循环之外简化标签
3. item 当前遍历数据的变量名
4. separator 分割符
-->
<select id="selectByIn" resultType="com.jt.pojo.User">
select * from user where id in(
<foreach collection="array" item="in" separator=",">
#{in}
</foreach>
)
</select>
动态SQL
1.根据对象中不为null的属性查询 <where>标签>加<if>标签(解决了将为null的属性进项查询的情况)
@Test
void contextLoadsId6() {
User user = new User();
user.setPhone("13111112222");
user.setStatus(true);
List<User> users=userMapper.selectByUser(user);
System.out.println(users);
}
xml sql
<select id="selectByUser" resultType="com.jt.pojo.User">
select * from user
<where>
<if test="id !=null">id = #{id}</if>
<if test="username !=null">and username = #{username}</if>
<if test="password !=null">and password = #{password}</if>
<if test="phone !=null">and phone = #{phone}</if>
<if test="email !=null">and emain = #{email}</if>
</where>
</select>
说一下<where> 标签的作用 本条sql传递的参数为 电话和用户状态 如果不加where标签
查询sql为 select * from user where and phone = (后边省略) where 后接and必定报错 而where标签的作用就是 干掉第一个and 确保sql正确
其中where标签也可以用where 1=1 代替 代码如下
<select id="selectByUser" resultType="com.jt.pojo.User">
select * from user
where 1=1
<if test="id !=null">id = #{id}</if>
<if test="username !=null">and username = #{username}</if>
<if test="password !=null">and password = #{password}</if>
<if test="phone !=null">and phone = #{phone}</if>
<if test="email !=null">and emain = #{email}</if>
</select>
因为1=1 永远为真 不会出现where是and的情况
select * from user where 1=1 and phone = (后边省略)