Mybatis之两种传参小方式
操作目的:更新数据库user表中的某条记录
方式一,多参数传值:
mapper中的方法
int updateUser(@Param("id") int id,@Param("name") String name);
userMapper中的sql
<update id="updateUser" >
update user
set name= #{name}
where id=#{id}
</update>
测试出类代码:
@Test
public void test(){
//获得sql对象
SqlSession sqlsession = null;
try {
sqlsession = Mybatis_util.getSqlsession();
//执行sql
userMapper mapper = sqlsession.getMapper(userMapper.class);
int i = mapper.updateUser(1,"小明");
if(i>0)
{
System.out.println("更新成功");
}
//提交事务
sqlsession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlsession.close();
}
}
方式二:map传值
mapper中的方法
int updatetUser2(Map<String,Object> map);
userMapper中的sql
<update id="updatetUser2" parameterType="map" >
update user
set name= #{name}
where id=#{id}
</update>
测试出类代码:
@Test
public void test(){
//获得sql对象
SqlSession sqlsession = null;
try {
sqlsession = Mybatis_util.getSqlsession();
//执行sql
userMapper mapper = sqlsession.getMapper(userMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("id",2);
map.put("name","小李");
int i = mapper.updatetUser2(map);
if(i>0)
{
System.out.println("更新成功");
}
//提交事务
sqlsession.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
sqlsession.close();
}
}