目录
-
mapper 接口中的方法涉及多参数问题
1. 如果是 insert 语句的话,可以将这些参数封装成 pojo 实体类对象,这样接口中就只需放一个实体类对象即可。
public interface UserMapper {
int insertUser(User user);
}
而对应的 **Mapper.xml文件中,paramterType 绑定好对应的实体类对象就行了,注意:返回值类型如果是 基本数据类型 的话,可以不用写,其他返回值类型就要。
<insert id="insertUser" parameterType="fun.lao.Myclass.User">
insert into t_user(logN, logP, name)
VALUES (#{logN}, #{logP}, #{name})
</insert>
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User u = new User("4836","ni4836","java程序猿");
int res = mapper.insertUser(u);
if(res > 0){
System.out.println("插入成功!");
//这里必须提交事务,否则不会插入的。默认自动提交关闭
sqlSession.commit();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(sqlSession != null){
sqlSession.close();
}
}
2. 如果是 select、update 语句的话,一般只需要修改其中的部分字段,所以就不能用上面的方法了。有以下两种方法:
1)在接口的方法中,用@Param(value = "") 逐个注释参数对应的字段
public interface UserMapper {
//value 对应的是SQL语句中的字段,跟实体类的属性没关系
int UpdateUser(@Param(value = "id")int no,@Param(value = "name")String name);
}
而此时,在**Mapper.xml文件中,连参数类型都不用写,因为在接口中已经声明了
<!--@Param()的方式,因为在接口中已经指明了参数名及类型,所以这里参数类型就不用写了-->
<update id="UpdateUser">
update t_user set name=#{name} where id=#{id}
</update>
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//直接使用接口的方法就行
int res = userMapper.UpdateUser(2,"张三");
if(res > 0){
System.out.println("更改成功!");
sqlSession.commit();
}
} catch (Exception e) {
e