MyBatis的动态SQL操作--插入

时间:2023-12-16 22:42:38

需求:向数据库中插入一条数据

//id,name,sal非空,三个字段都插入
insert into student(id,name,sal) values (?,?,?)
//id,name非空,只对id和name插入值
insert into student(id,name) values (?,?)
//id,sal非空
insert into student(id,sal) values (?,?)

为null的字段忽略掉.

<?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>
<!-- sql片段对应字段名,id属性值任意 -->
<sql id="key">
<!-- 去掉最后一个, -->
<trim suffixOverrides=",">
       //id是类的属性名
<if test="id!=null">
         //id是表的字段名
id,</if>
       //name是类的属性名
<if test="name!=null">
         //name是表的字段名
name,
</if>
       //sal是类的属性名
<if test="sal!=null">
         //sal是表的字段名
sal,
</if>
</trim>
</sql> <!-- sql片段对应?,id属性值任意 -->
<sql id="value">
<!-- 去掉最后一个, -->
<trim suffixOverrides=",">
<if test="id!=null">
#{id},//肯定是调用了get方法得到的值,所以是实体类中的属性名
</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="Student">
INSERT INTO student(<include refid="key"/>) VALUES(<include refid="value"/>)
</insert>
</mapper>
public class StudentDao {
/**
* 插入学生
*/
public void dynaInsert(Student student) throws Exception{
SqlSession sqlSession = null;
try{
sqlSession = MybatisUtil.getSqlSession();
sqlSession.insert(Student.class.getName() + ".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,"zhangsan1",1000d));//insert into 表名(*,*,*) values(?,?,?)
//dao.dynaInsert(new Student(3,"lisi",null));//insert into 表名(*,*) values(?,?)
dao.dynaInsert(new Student(5,null,7000D));//insert into 表名(*,*) values(?,?)
//dao.dynaInsert(new Student(4,null,null));//insert into 表名(*) values(?)
}
}