@Param方法
- @Param 方法就是使用注解的方式
- UsersMapper.java
public interface UsersMapper {
public Users selectUser(@Param("id")int id, @Param("userName") String name);
}
- @Param("id") 就是告诉 mybatis , 参数 id 在 SQL 语句中用 id 作为 key。
也就是说, mybatis 帮我们完成了调用时, 类似 params.put("id","id") 这个过程
实体类User实现传参
- UsersMapper.java
public interface UsersMapper {
public List<Users> getUserListByUser(Users user);
}
- userMapper.xml
<?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,namespace的值习惯上设置成包名+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.java
@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实现传参
- UsersMapper.java
public interface UsersMapper {
public List<Users> getUserListByMap(Map<String,String> userMap);
}
- UsersMapper.xml
<?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,namespace的值习惯上设置成包名+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.java
@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());
}
}