错误案例:
Service接口:
package com.wen.service.user;
import java.util.List;
import com.wen.bean.User;
//用户登录
public interface UserServices {
User getUserByLoigin(String student_id, String password);
}
实现类:
package com.wen.service.impl.user;
import java.util.List;
import javax.annotation.Resource;
import com.wen.bean.User;
import com.wen.mapper.user.UserMapper;
import com.wen.service.user.UserServices;
public class UserServicesImpl implements UserServices {
@Resource
UserMapper userMapper;
@Override
public User getUserByLoigin(String student_id,String password) {
return userMapper.getUserByLoigin(student_id,password);
}
}
Mybatis的mapper接口及配置文件:
package com.wen.mapper.user;
import com.wen.bean.User;
public interface UserMapper {
User getUserByLoigin(String student_id,String password) throws RuntimeException;
}
xml配置文件:(主要错误就是:Mybatis找不到传进去的参数,就像where里面的student_id,password这两个字段)
<?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.wen.mapper.user.UserMapper">
<!-- resulType中的 user 是别名 在sqlMapperConfig.xml中配置了扫描别名,别名一般为类名的小写 -->
<select id="getUserByLoigin" resultType="user" parameterType="String">
select
* from user
<where>
student_id=#{student_id,jdbcType=VARCHAR}
and
password=#{password,jdbcType=VARCHAR}
</where>
</select>
</mapper>
修改如下:
注意事项:(不能用parameterType这个属性了,多个参数情况下)
解决方案:
方法一:将student_id改成0,password改成1!表示将第一个参数,第二个参数放入。这种是指定索引的方法,有几个参数就对应几个索引。
<select id="getUserByLoigin" resultType="user">
select
* from user
<where>
student_id=#{0,jdbcType=VARCHAR}
and
password=#{1,jdbcType=VARCHAR}
</where>
</select>
方法二:如果非要用参数原名字的话!就在mapper接口处加@Param("名字")这个注解!这样,就可以使用原来的参数名一致了。这种方式实际上在@Param这个注解就会被Mybatis自动封装成Map集合类型!
package com.wen.mapper.user;
import com.wen.bean.User;
public interface UserMapper {
User getUserByLoigin(@Param("student_id")String student_id,@Param("password") String password) throws RuntimeException;}
总结:
在学习Mybatis中,可能会遇到传各种参数问题。但是,Mybatis的传递传输在mapper中又是不同的,对象和单个参数,多个参数都是不同。当然还有其他传值方式,比如list,map等就不一一介绍了!
程序人生,与君共勉