mybatis更新學習筆記
阿新 • • 發佈:2018-04-24
mybatis更新學習筆記
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import cn.itcast.javaee.mybatis.util.MybatisUtil;
/**
* 持久層
* @author AdminTC
*/
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 HashMap<String, Object>();
map.put("pid",id);
map.put("pname",name);
map.put("psal",sal);
sqlSession.update("studentNamespace.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();
//關註SQL的變化
//dao.dynaUpdate(1,null,9000D);//update students set sal=? where id=?
//dao.dynaUpdate(1,"笨笨",null);//update students set name=? where id=?
dao.dynaUpdate(1,"笨笨",10000D);//update students set name=? and sal=? where id=?
}
}
<?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="studentNamespace"> <resultMap type="cn.itcast.javaee.mybatis.app12.Student" id="studentMap"> <id property="id" column="students_id"/> <result property="name" column="students_name"/> <result property="sal" column="students_sal"/> </resultMap> <!-- set標簽自動判斷哪個是最後一個字段,會自動去掉最後一個,號 --> <update id="dynaUpdate" parameterType="map"> update students <set> <if test="pname!=null"> students_name = #{pname}, </if> <if test="psal!=null"> students_sal = #{psal}, </if> </set> where students_id = #{pid} </update> </mapper>
mybatis更新學習筆記