mybatis进行模糊查询的几种方式

mapper文件:

<?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.joymeng.war.db.dao.UserDao">
<!--设置User类和数据库中表的字段一一对应! -->
<resultMap id="BaseResultMap" type="user">
<id column="USER_ID" property="userId" jdbcType="INTEGER" />
<result column="USER_NAME" property="userName" jdbcType="CHAR" />
<result column="USER_PASSWORD" property="userPassword" jdbcType="CHAR" />
<result column="USER_EMAIL" property="userEmail" jdbcType="CHAR" />
</resultMap>
<!-- 根据Id查询单条记录 -->
<select id="selectUserById" parameterType="int" resultMap="BaseResultMap">
SELECT * FROM t_user WHERE USER_ID = #{userId}
</select>

<!-- 根据名称查询符合条件的记录 -->
<select id="selectUsersByNameLike" parameterType="String" resultMap="BaseResultMap">
<!-- 模糊查询方法0 参数中直接拼好 -->
<!-- 模糊查询方法1 CONCAT -->
<!-- SELECT * FROM t_user WHERE USER_NAME LIKE CONCAT('%',#{name},'%') -->

<!-- 模糊查询方法2 bind标签进行参数处理(只允许单个参数): _parameter为参数信息 -->
<bind name="name" value="'%' + _parameter + '%'" />
SELECT * FROM t_user WHERE USER_NAME LIKE #{name}
</select>

<!-- 根据名称和id查询符合条件的记录 -->
<select id="selectUsersByNameLikeAndId" parameterType="HashMap" resultMap="BaseResultMap">
<!-- 模糊查询方法2 bind标签进行参数处理(多参数处理):添加注解@Param("pname") -->
<bind name="namenew" value="'%' + pname + '%'" />
SELECT * FROM t_user WHERE USER_NAME LIKE #{namenew} AND USER_ID>#{puserId}
</select>
</mapper>

对应的Dao文件:

public interface UserDao {
  public User selectUserById(Integer userId);

  public List<User> selectUsersByNameLike(String name);

  public List<User> selectUsersByNameLikeAndId(@Param("pname") String name, @Param("puserId")Integer userId);
}

猜你喜欢

转载自blog.csdn.net/gaoshan12345678910/article/details/81366602