1
Import Java.util.arraylist;import Java.util.list;import Org.apache.ibatis.session.sqlsession;import cn.itcast.javaee.mybatis.util.mybatisutil;/** * Persistence layer * @author ADMINTC */public class Studentdao {/** * Insert student * /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, "haha", 7000D));//insert into table name (*,*,*) VALUES (?,?,?) Dao.dynainsert (New Student (2, "haha", null));//insert into table name (*,*) VALUES (?,?) Dao.dynainsert (New Student (3,null,7000d));//insert into table name (*,*) VALUES (?,?) Dao.dynainsert (New Student (4,null,null));//insert into table name (*) 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 fragment corresponding field name, id attribute value--- <sql id= "Key" > <!--Remove the last one,--<trim suffixoverrides= "," > <if test= "Id!=nul L "> students_id, </if> <if test=" Name!=null "> Students_ Name, </if> <if test= "Sal!=null" > Students_sal, </if> </trim> </sql> <!--sql fragment corresponding?, id attribute value any--<sql id= "value" > <!--Remove the last-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"/> and <include refid= "value"/> means referencing the SQL snippet defined above--<insert id= "Dynains ert "parametertype=" cn.itcast.javaee.mybatis.app14.Student "> INSERT into Students (<include refid=" key "/>) VALUES (<include refid= "value"/>) </insert></mapper>
Insert Learning notes for MyBatis Dynamic SQL operations