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標簽進行參數處理(只允許單個參數
<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標簽進行參數處理(多參數
<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);
}
mybatis進行模糊查詢的幾種方式