Mybatis使用select条件查询的几种方式
1. 单条件查询
UserMapper.java
public interface UserMapper {
//通过用户名单条件查询
public List<User> getUserListByUserName(String userName);
}
UserMapper.xml
<select id="getUserListByUserName" resultType="User" parameterType="String">
select * from smbms_user WHERE userName LIKE CONCAT('%',#{userName},'%')
</select>
2.多条件查询(将查询条件封装成对象入参)
UserMapper.java
public interface UserMapper {
//通过用户名和密码多条件查询
public List<User> getUserListByUserNameAndPassword(User user);
}
UserMapper.xml
<select id="getUserListByUserNameAndPassword" resultType="User" parameterType="User">
select * from smbms_user WHERE userName LIKE CONCAT('%',#{userName},'%') and userPassword = #{userPassword}
</select>
3.多条件查询(将查询条件封装成Map对象入参)
UserMapper.java
public interface UserMapper {
//Map通过用户名和密码多条件查询
public List<User> getUserListByMap(Map<String, String> userMap);
}
UserMapper.xml
<select id="getUserListByMap" resultType="User" parameterType="Map">
select * from smbms_user WHERE userName LIKE CONCAT('%',#{userName},'%') and userPassword = #{userPassword}
</select>
//这种做法更加灵活,不管是什么类型的参数,或者多少个参数,我们都可以把它封装成Map数据结构进行入参,通过Map即可获取传入的值。
4.使用@param注解实现多参数入参(4个参数以下推荐使用)
UserMapper.java
public interface UserMapper {
//注解@param:通过用户名和密码多条件查询
public List<User> getUserListByParam(@Param("userName")String userName,@param("userPassword")String userPassword)
}
UserMapper.xml
<select id="getUserListByParam" resultType="User">
select * from smbms_user WHERE userName LIKE CONCAT('%',#{userName},'%') and userPassword = #{userPassword}
</select>
//用@Param来指定哪一个,就不能使用parameterType
5.使用@param注解实现多参数入参(第二种)
UserMapper.java
public interface UserMapper {
public List<User> getUserListByUserIdAndPwd(String userName,String userPassword);
}
<select id="getUserListByUserIdAndPwd" resultType="User" >//不需要写parameterType参数
SELECT * FROM smbms_user WHERE userName= #{0} and userPassword= #{1}
</select>
//#{index}是第几个就用第几个的索引,索引从0开始