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>
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!
posted on 2018-12-04 15:40 LoaderMan 阅读(5480) 评论(0) 编辑 收藏 举报