多参数查询

Exisi 2021-03-27 07:23:31
Categories: Tags:

@Param方法

 

 

public interface UsersMapper {

 

public Users selectUser(@Param("id")int id, @Param("userName") String name);

 

}

 

也就是说, mybatis 帮我们完成了调用时, 类似 params.put("id","id") 这个过程

 

 

实体类User实现传参

 

 

public interface UsersMapper {

 

public List<Users> getUserListByUser(Users user);

 

}

 

 

 

<?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指定一个唯一的namespacenamespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的

<mapper namespace="com.mybatis.dao.UsersMapper">

 

 

<select id="getUserList" parameterType="Users" resultType="User">

select * from smbms_user where userName like CONCAT('%',#{userName},'%')

 

</select>

 

</mapper>

 

 

 

@Test

//多参数查询(Users)

public void testGetUserList() {

SqlSession sqlSession=null;

List<Users> userList =new ArrayList<Users>();

try{

sqlSession=MyBatisUtil.createSqlSession();

 

Users user=new Users();

user.setUserName("");

user.setUserRole("3");

userList=sqlSession.getMapper(UsersMapper.class).getUserListByUser(user);

 

}catch(Exception e){

e.printStackTrace();

}finally{

MyBatisUtil.closeSqlSession(sqlSession);

}

for(Users user:userList) {

System.out.println(user.getUserName());

}

}

 

 

 

 

Map实现传参

 

 

public interface UsersMapper {

 

public List<Users> getUserListByMap(Map<String,String> userMap);

 

}

 

 

 

<?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指定一个唯一的namespacenamespace的值习惯上设置成包名+sql映射文件名,这样就能够保证namespace的值是唯一的

<mapper namespace="com.mybatis.dao.UsersMapper">

 

 

<select id="getUserList" parameterType="Map" resultType="Users">

select * from smbms_user where userName like CONCAT('%',#{userName},'%') and userRole=#{userRole}

 

</select>

 

</mapper>

 

 

 

@Test

//多参数查询(Users)

public void testGetUserList() {

SqlSession sqlSession=null;

List<Usesr> userList =new ArrayList<Users>();

try{

sqlSession=MyBatisUtil.createSqlSession();

 

Map<String,String> userMap=new HashMap<String,String>();

userMap.put("userName", "");

userMap.put("userRole", "3");

userList=sqlSession.getMapper(UsersMapper.class).getUserListByMap(userMap);

 

}catch(Exception e){

e.printStackTrace();

}finally{

MyBatisUtil.closeSqlSession(sqlSession);

}

for(Users user:userList) {

System.out.println(user.getUserName());

}

}