Mybatis中的模糊查询
这里以实现SpecialSQLMapper接口的方法为例,来用代码展示myBatis中的模糊查询
package com.qcw.mybatis.mapper;
import com.qcw.mybatis.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SpecialSQLMapper {
//通过通过用户名模糊查询
List<User> getUserByLike(@Param("vague") String vague);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcw.mybatis.mapper.SpecialSQLMapper">
<!-- List<User> getUserByLike(@Param("vague") String vague);-->
<select id="getUserByLike" resultType="User">
<!--select * from t_user where username like '%${vague}%'-->
<!--select * from t_user where username like concat('%',#{vague},'%')-->
select * from t_user where username like "%"#{vague}"%"
</select>
</mapper>
package com.qcw.mybatis.test;
import com.qcw.mybatis.mapper.SpecialSQLMapper;
import com.qcw.mybatis.pojo.User;
import com.qcw.mybatis.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class SpecialMapperTest {
@Test
public void getUserByLikeTest(){
SqlSession sqlSession = SqlSessionUtil.getSqlSession();
SpecialSQLMapper mapper = sqlSession.getMapper(SpecialSQLMapper.class);
List<User> list = mapper.getUserByLike("a");
list.forEach(System.out::println);
}
}