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>
  • 相关阅读:
    C++11并发内存模型学习
    C++0x对局部静态初始化作出了线程安全的要求,singleton的写法可以回归到最原始的方式
    两次fopen不同的文件返回相同的FILE* 地址
    linux kernel kill jvm
    打印Exception信息
    java map value 排序
    java was started but returned exit code 1
    hive 建表语句
    hadoop mapreduce lzo
    分词 正文提取 java
  • 原文地址:https://www.cnblogs.com/loaderman/p/10064477.html
Copyright © 2011-2022 走看看