1.StudentDo
package cn.itcast.app05;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import cn.itcast.util.MybatisUtil;
public class StudentDao {
public void dynaUpdate(Integer id,String name,Double sal) throws Exception{
SqlSession sqlSession=null;
try{
sqlSession=MybatisUtil.getSqlSession();
Map<String,Object> map=new LinkedHashMap<String,Object>();
map.put("pid", id);
map.put("pname", name);
map.put("psal",sal);
sqlSession.update(Student.class.getName()+".dynaUpdate", map);
sqlSession.commit();
}catch(Exception e){
e.printStackTrace();
sqlSession.rollback();
throw e;
}finally{
MybatisUtil.closeSqlSession();
}
}
//测试
public static void main(String[] args) throws Exception{
StudentDao dao=new StudentDao();
dao.dynaUpdate(1,null,9000D);
}
}
2.映射文件
<?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="cn.itcast.app05.Student">
<resultMap type="cn.itcast.app05.Student" id="studentMap">
<id property="id" column="id"></id>
<result property="name" column="name"/>
<result property="sal" column="sal"/>
</resultMap>
<update id="dynaUpdate" parameterType="map">
update students
<set>
<if test="pname!=null">
name=#{pname},
</if>
<if test="psal!=null">
sal=#{psal},
</if>
</set>
where id=#{pid};
</update>
</mapper>