mybatis之动态SQL操作之插入

1)  根据条件,插入一个学生

/**
 * 持久层*/
public class StudentDao {
    /**
     * 动态SQL--插入
     */
    public void dynaSQLwithInsert(Student student) throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            sqlSession.insert("mynamespace.dynaSQLwithInsert",student);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MyBatisUtil.closeSqlSession();
        }
    }
    public static void main(String[] args) throws Exception{
        StudentDao dao = new StudentDao();
        dao.dynaSQLwithInsert(new Student(1,"哈哈",7000D));
        dao.dynaSQLwithInsert(new Student(2,"哈哈",null));
        dao.dynaSQLwithInsert(new Student(3,null,7000D));
    }
}
<?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="mynamespace">
    <sql id="key">
        <trim suffixOverrides=",">
            <if test="id!=null">
                id,
            </if>
            <if test="name!=null">
                name,
            </if>
            <if test="sal!=null">
                sal,
            </if>
        </trim>
    </sql>
    <sql id="value">
        <trim suffixOverrides=",">
            <if test="id!=null">
                #{id},
            </if>
            <if test="name!=null">
                #{name},
            </if>
            <if test="sal!=null">
                #{sal},
            </if>
        </trim>
    </sql>
    <insert id="dynaSQLwithInsert" parameterType="loaderman.Student">
        insert into students(<include refid="key"/>) values(<include refid="value"/>)
    </insert>
</mapper>

 

posted on 2018-12-04 15:40  LoaderMan  阅读(5480)  评论(0编辑  收藏  举报

导航