MyBatis的動態SQL操作--更新


更新條件不確定,需要根據具體的情況生成sql語句.

id是主鍵,一般不會去更新。

1.只更新name的值

update student set name = ? where id = ?

2.只更新sal的值

update student set sal = ? where id = ?

3.同時更新name和sal的值

update student set sal = ? , name = ? 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">

<!-- namespace的取值可以是實體的全限定名,這樣有好處! -->
<mapper namespace="com.winner.entity.Student">
    <resultMap id="studentMap" type="student">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="sal" column="sal"/>
    </resultMap>
    <!-- set標簽自動判斷哪個是最后一個字段,會自動去掉最后一個,號 -->
    <update id="dynaUpdate" parameterType="map"> UPDATE student <set>
            <if test="pname!=null"> name = #{pname},//不要忘了, </if>
            <if test="psal!=null"> sal = #{psal},//不要忘了, </if>
        </set> WHERE id = #{pid} </update>
</mapper>
public class StudentDao { /** * 有條件更新學生 */
    public void dynaUpdate(Integer id,String name,Double sal) throws Exception{ SqlSession sqlSession = null; try{ sqlSession = MybatisUtil.getSqlSession();        //map用於接收方法的參數,xml中參數的類型就是map Map<String,Object> map = new HashMap<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(); //關注SQL的變化 //dao.dynaUpdate(1,null,9000D);//update student set sal=? where id=? //dao.dynaUpdate(1,"lisi",null);//update student set name=? where id=?
        dao.dynaUpdate(1,"wangwu",8000D);//update student set name=? and sal=? where id=?
 } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM