zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    灰度图转换
    OGRE分析之文件系统 (1)
    屏幕截图
    [GP]template必须定义于头文件中
    OGRE分析之设计模式
    ON_COMMAND_RANGE和ON_UPDATE_COMMAND_UI_RANGE
    使用SkinMagic Toolkit美化界面(II)
    Single Sign On for Windows and Linux
    "C compiler cannot create executables"
    How to Create a First C Program on Linux
  • 原文地址:https://www.cnblogs.com/loaderman/p/10064477.html
Copyright © 2011-2022 走看看