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