mybatis动态SQL操作之插入学习笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis动态SQL操作之插入学习笔记相关的知识,希望对你有一定的参考价值。

1


import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import cn.itcast.javaee.mybatis.util.MybatisUtil;

/**
 * 持久层 
 * @author AdminTC
 */
public class StudentDao {
    /**
     * 插入学生
     */
    public void dynaInsert(Student student) throws Exception{
        SqlSession sqlSession = null;
        try{
            sqlSession = MybatisUtil.getSqlSession();
            sqlSession.insert("studentNamespace.dynaInsert",student);
            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();
        //dao.dynaInsert(new Student(1,"哈哈",7000D));//insert into 表名(*,*,*) values(?,?,?)
        //dao.dynaInsert(new Student(2,"哈哈",null));//insert into 表名(*,*) values(?,?)
        //dao.dynaInsert(new Student(3,null,7000D));//insert into 表名(*,*) values(?,?)
        dao.dynaInsert(new Student(4,null,null));//insert into 表名(*) values(?)
    }
}

2

<?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="studentNamespace">   

    <resultMap type="cn.itcast.javaee.mybatis.app14.Student" id="studentMap">
        <id property="id" column="students_id"/>
        <result property="name" column="students_name"/>
        <result property="sal" column="students_sal"/>
    </resultMap>

    <!-- sql片段对应字段名,id属性值任意 -->
    <sql id="key">
        <!-- 去掉最后一个, -->
        <trim suffixOverrides=",">
            <if test="id!=null">
                students_id,
            </if>
            <if test="name!=null">
                students_name,
            </if>
            <if test="sal!=null">
                students_sal,
            </if>
        </trim>
    </sql>

    <!-- sql片段对应?,id属性值任意 -->
    <sql id="value">
        <!-- 去掉最后一个 -trim suffixOverrides, -->
        <trim suffixOverrides=",">
            <if test="id!=null">
                #{id},
            </if>
            <if test="name!=null">
                #{name},
            </if>
            <if test="sal!=null">
                #{sal},
            </if>
        </trim>
    </sql>

    <!-- <include refid="key"/>和<include refid="value"/>表示引用上面定义的sql片段 -->
    <insert id="dynaInsert" parameterType="cn.itcast.javaee.mybatis.app14.Student">
        insert into students(<include refid="key"/>) values(<include refid="value"/>)
    </insert>

</mapper>

以上是关于mybatis动态SQL操作之插入学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

MyBatis-05-笔记

JavaWeb学习笔记之Mybatis实用sql语句汇总

JavaWeb学习笔记之Mybatis实用sql语句汇总

Mybatis学习笔记:动态SQL

Mybatis -- 动态Sql概述动态Sql之<if>(包含<where>)动态Sql之<foreach>sql片段抽取

MyBatis之动态SQL