动态SQL之模糊查询

Posted 菜包包

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态SQL之模糊查询相关的知识,希望对你有一定的参考价值。

模糊查询学习了三种:

DAO层

// 可以使用
List<User> wherelike01(String user_name);

// 忘记
List<User> wherelike02(Map<String, Object> map);

// 推荐使用
List<User> wherelike03(String user_name)

测试类

 

@Test
    public void where语句测试01() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            sqlSession.getMapper(UserDao.class).wherelike01("宋%");
        } catch (Exception e) {
            logger.debug(e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }
@Test
    public void where语句测试02$() {
        SqlSession sqlSession = null;
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("account", "宋");
            sqlSession = MyBatisUtils.getSqlSession();
            sqlSession.getMapper(UserDao.class).wherelike02(map);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }
@Test
public void where语句测试03推荐() {
  SqlSession sqlSession = null;
  try {
    sqlSession = MyBatisUtils.getSqlSession();
    sqlSession.getMapper(UserDao.class).wherelike03("宋");
    } catch (Exception e) {
      logger.debug(e.getMessage());
      throw new RuntimeException(e.getMessage());
    } finally {
      MyBatisUtils.closeSqlSession(sqlSession);
    }
}

Mapper中 

<mapper namespace="com.shxt.dao.UserDao">
       <select id="wherelike01" parameterType="string" resultType="com.shxt.model.User">
         SELECT
            *
        FROM
            USER
        WHERE
            user_name LIKE #{user_name}
       </select>
        <select id="wherelike02" parameterType="map" resultType="com.shxt.model.User">
           SELECT
                *
            FROM
                USER
            WHERE
                user_name LIKE ‘${user_name}%‘
       </select>
         <select id="wherelike03" parameterType="string" resultType="com.shxt.model.User">
           SELECT
                *
            FROM
                USER
            WHERE
                user_name LIKE CONCAT(#{user_name}, ‘%‘)
       </select>
</mapper>

  

以上是关于动态SQL之模糊查询的主要内容,如果未能解决你的问题,请参考以下文章

Mybatis——Dao层实现映射文件深入核心配置文件深入

在JSP页面通过form表单传递5个模糊查询的条件 如何 在底层 写模糊查询 方法

java模糊关键字查询

java中Action层Service层和Dao层的功能区分

java中Action层Service层和Dao层的功能区分

jsp如何按指定条件进行模糊查询