
MyBatis 虽说给我们的开发带来了很多的便捷但有些地方写起来依旧比较的麻烦比如配置XML的时候但是一个好的写法不仅能为我们节省不少时间、还能能降低出错的概率下面就给大家分享一些优质的写法1、用来循环容器的标签forEachforeach元素的属性主要有itemindexcollectionopenseparatorclose。item集合中元素迭代时的别名index集合中元素迭代时的索引open常用语where语句中表示以什么开始比如以(开始separator表示在每次进行迭代时的分隔符close 常用语where语句中表示以什么结束在使用foreach的时候最关键的也是最容易出错的就是collection属性该属性是必须指定的但是在不同情况下该属性的值是不一样的主要有一下3种情况如果传入的是单参数且参数类型是一个List的时候collection属性值为list .如果传入的是单参数且参数类型是一个array数组的时候collection的属性值为array .如果传入的参数是多个的时候我们就需要把它们封装成一个Map了当然单参数也可以封装成map实际上如果你在传入参数的时候在MyBatis里面也是会把它封装成一个Map的map的key就是参数名所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key.针对最后一条我们来看一下官方说法注意 你可以将一个 List 实例或者数组作为参数对象传给 MyBatis当你这么做的时候MyBatis 会自动将它包装在一个 Map 中并以名称为键。List 实例将会以“list”作为键而数组实例的键将是“array”。所以不管是多参数还是单参数的list,array类型都可以封装为map进行传递。如果传递的是一个List则mybatis会封装为一个list为keylist值为object的map如果是array则封装成一个array为keyarray的值为object的map如果自己封装呢则colloection里放的是自己封装的map里的key值//mapper中我们要为这个方法传递的是一个容器,将容器中的元素一个一个的 //拼接到xml的方法中就要使用这个forEach这个标签了 public ListEntity queryById(ListString userids); //对应的xml中如下 select idqueryById resultMapBaseReslutMap select * FROM entity where id in foreach collectionuserids itemuserid indexindex open( separator, close) #{userid} /foreach /select2、concat模糊查询//比如说我们想要进行条件查询,但是几个条件不是每次都要使用,那么我们就可以 //通过判断是否拼接到sql中 select idqueryById resultMapBascResultMap parameterTypeentity SELECT * from entity where if testname!null name like concat(%,concat(#{name},%)) /if /where /select3、choose (when, otherwise)标签choose标签是按顺序判断其内部when标签中的test条件出否成立如果有一个成立则 choose 结束。当 choose 中所有 when 的条件都不满则时则执行 otherwise 中的sql。类似于Java 的 switch 语句choose 为 switchwhen 为 caseotherwise 则为 default。关注码猿技术专栏回复关键词1111 获取阿里内部Java性能调优手册例如下面例子同样把所有可以限制的条件都写上方面使用。choose会从上到下选择一个when标签的test为true的sql执行。安全考虑我们使用where将choose包起来放置关键字多于错误。!-- choose(判断参数) - 按顺序将实体类 User 第一个不为空的属性作为where条件 -- select idgetUserList_choose resultMapresultMap_user parameterTypecom.yiibai.pojo.User SELECT * FROM User u where choose when testusername !null u.username LIKE CONCAT(CONCAT(%, #{username, jdbcTypeVARCHAR}),%) /when when testsex ! null and sex ! AND u.sex #{sex, jdbcTypeINTEGER} /when when testbirthday ! null AND u.birthday #{birthday, jdbcTypeDATE} /when otherwise /otherwise /choose /where /select4、selectKey 标签在insert语句中在Oracle经常使用序列、在MySQL中使用函数来自动生成插入表的主键而且需要方法能返回这个生成主键。使用myBatis的selectKey标签可以实现这个效果。下面例子使用mysql数据库自定义函数nextval(student)用来生成一个key并把他设置到传入的实体类中的studentId属性上。所以在执行完此方法后边可以通过这个实体类获取生成的key。!-- 插入学生 自动主键-- insert idcreateStudentAutoKey parameterTypeliming.student.manager.data.model.StudentEntity keyPropertystudentId selectKey keyPropertystudentId resultTypeString orderBEFORE select nextval(student) /selectKey INSERT INTO STUDENT_TBL(STUDENT_ID, STUDENT_NAME, STUDENT_SEX, STUDENT_BIRTHDAY, STUDENT_PHOTO, CLASS_ID, PLACE_ID) VALUES (#{studentId}, #{studentName}, #{studentSex}, #{studentBirthday}, #{studentPhoto, javaTypebyte[], jdbcTypeBLOB, typeHandlerorg.apache.ibatis.type.BlobTypeHandler}, #{classId}, #{placeId}) /insert调用接口方法和获取自动生成keyStudentEntity entity new StudentEntity(); entity.setStudentName(黎明你好); entity.setStudentSex(1); entity.setStudentBirthday(DateUtil.parse(1985-05-28)); entity.setClassId(20000001); entity.setPlaceId(70000001); this.dynamicSqlMapper.createStudentAutoKey(entity); System.out.println(新增学生ID: entity.getStudentId());5、if标签if标签可用在许多类型的sql语句中我们以查询为例。首先看一个很普通的查询!-- 查询学生listlike姓名 -- select idgetStudentListLikeName parameterTypeStudentEntity resultMapstudentResultMap SELECT * from STUDENT_TBL ST WHERE ST.STUDENT_NAME LIKE CONCAT(CONCAT(%, #{studentName}),%) /select但是此时如果studentName为null此语句很可能报错或查询结果为空。此时我们使用if动态sql语句先进行判断如果值为null或等于空字符串我们就不进行此条件的判断增加灵活性。参数为实体类StudentEntity。将实体类中所有的属性均进行判断如果不为空则执行判断条件。!-- 2 if(判断参数) - 将实体类不为空的属性作为where条件 -- select idgetStudentList_if resultMapresultMap_studentEntity parameterTypeliming.student.manager.data.model.StudentEntity SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST WHERE if teststudentName !null ST.STUDENT_NAME LIKE CONCAT(CONCAT(%, #{studentName, jdbcTypeVARCHAR}),%) /if if teststudentSex ! null and studentSex ! AND ST.STUDENT_SEX #{studentSex, jdbcTypeINTEGER} /if if teststudentBirthday ! null AND ST.STUDENT_BIRTHDAY #{studentBirthday, jdbcTypeDATE} /if if testclassId ! null and classId! AND ST.CLASS_ID #{classId, jdbcTypeVARCHAR} /if if testclassEntity ! null and classEntity.classId !null and classEntity.classId ! AND ST.CLASS_ID #{classEntity.classId, jdbcTypeVARCHAR} /if if testplaceId ! null and placeId ! AND ST.PLACE_ID #{placeId, jdbcTypeVARCHAR} /if if testplaceEntity ! null and placeEntity.placeId ! null and placeEntity.placeId ! AND ST.PLACE_ID #{placeEntity.placeId, jdbcTypeVARCHAR} /if if teststudentId ! null and studentId ! AND ST.STUDENT_ID #{studentId, jdbcTypeVARCHAR} /if /select使用时比较灵活 new一个这样的实体类我们需要限制那个条件只需要附上相应的值就会where这个条件相反不去赋值就可以不在where中判断。public void select_test_2_1() { StudentEntity entity new StudentEntity(); entity.setStudentName(); entity.setStudentSex(1); entity.setStudentBirthday(DateUtil.parse(1985-05-28)); entity.setClassId(20000001); //entity.setPlaceId(70000001); ListStudentEntity list this.dynamicSqlMapper.getStudentList_if(entity); for (StudentEntity e : list) { System.out.println(e.toString()); } }6、if where 的条件判断当where中的条件使用的if标签较多时这样的组合可能会导致错误。我们以在3.1中的查询语句为例子当java代码按如下方法调用时Test public void select_test_2_1() { StudentEntity entity new StudentEntity(); entity.setStudentName(null); entity.setStudentSex(1); ListStudentEntity list this.dynamicSqlMapper.getStudentList_if(entity); for (StudentEntity e : list) { System.out.println(e.toString()); } }如果上面例子参数studentName为null将不会进行STUDENT_NAME列的判断则会直接导“WHERE AND”关键字多余的错误SQL。这时我们可以使用where动态语句来解决。这个“where”标签会知道如果它包含的标签中有返回值的话它就插入一个‘where’。此外如果标签返回的内容是以AND 或OR 开头的则它会剔除掉。上面例子修改为!-- 3 select - where/if(判断参数) - 将实体类不为空的属性作为where条件 -- select idgetStudentList_whereIf resultMapresultMap_studentEntity parameterTypeliming.student.manager.data.model.StudentEntity SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST where if teststudentName !null ST.STUDENT_NAME LIKE CONCAT(CONCAT(%, #{studentName, jdbcTypeVARCHAR}),%) /if if teststudentSex ! null and studentSex ! AND ST.STUDENT_SEX #{studentSex, jdbcTypeINTEGER} /if if teststudentBirthday ! null AND ST.STUDENT_BIRTHDAY #{studentBirthday, jdbcTypeDATE} /if if testclassId ! null and classId! AND ST.CLASS_ID #{classId, jdbcTypeVARCHAR} /if if testclassEntity ! null and classEntity.classId !null and classEntity.classId ! AND ST.CLASS_ID #{classEntity.classId, jdbcTypeVARCHAR} /if if testplaceId ! null and placeId ! AND ST.PLACE_ID #{placeId, jdbcTypeVARCHAR} /if if testplaceEntity ! null and placeEntity.placeId ! null and placeEntity.placeId ! AND ST.PLACE_ID #{placeEntity.placeId, jdbcTypeVARCHAR} /if if teststudentId ! null and studentId ! AND ST.STUDENT_ID #{studentId, jdbcTypeVARCHAR} /if /where /select7、if set实现修改语句当update语句中没有使用if标签时如果有一个参数为null都会导致错误。当在update语句中使用if标签时如果前面的if没有执行则或导致逗号多余错误。使用set标签可以将动态的配置SET 关键字和剔除追加到条件末尾的任何不相关的逗号。使用ifset标签修改后如果某项为null则不进行更新而是保持数据库原值。如下示例!-- 4 if/set(判断参数) - 将实体类不为空的属性更新 -- update idupdateStudent_if_set parameterTypeliming.student.manager.data.model.StudentEntity UPDATE STUDENT_TBL set if teststudentName ! null and studentName ! STUDENT_TBL.STUDENT_NAME #{studentName}, /if if teststudentSex ! null and studentSex ! STUDENT_TBL.STUDENT_SEX #{studentSex}, /if if teststudentBirthday ! null STUDENT_TBL.STUDENT_BIRTHDAY #{studentBirthday}, /if if teststudentPhoto ! null STUDENT_TBL.STUDENT_PHOTO #{studentPhoto, javaTypebyte[], jdbcTypeBLOB, typeHandlerorg.apache.ibatis.type.BlobTypeHandler}, /if if testclassId ! STUDENT_TBL.CLASS_ID #{classId} /if if testplaceId ! STUDENT_TBL.PLACE_ID #{placeId} /if /set WHERE STUDENT_TBL.STUDENT_ID #{studentId}; /update8、if trim代替where/set标签trim是更灵活的去处多余关键字的标签他可以实践where和set的效果。trim代替where!-- 5.1if/trim代替where(判断参数) -将实体类不为空的属性作为where条件-- select idgetStudentList_if_trim resultMapresultMap_studentEntity SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST trim prefixWHERE prefixOverridesAND|OR if teststudentName !null ST.STUDENT_NAME LIKE CONCAT(CONCAT(%, #{studentName, jdbcTypeVARCHAR}),%) /if if teststudentSex ! null and studentSex ! AND ST.STUDENT_SEX #{studentSex, jdbcTypeINTEGER} /if if teststudentBirthday ! null AND ST.STUDENT_BIRTHDAY #{studentBirthday, jdbcTypeDATE} /if if testclassId ! null and classId! AND ST.CLASS_ID #{classId, jdbcTypeVARCHAR} /if if testclassEntity ! null and classEntity.classId !null and classEntity.classId ! AND ST.CLASS_ID #{classEntity.classId, jdbcTypeVARCHAR} /if if testplaceId ! null and placeId ! AND ST.PLACE_ID #{placeId, jdbcTypeVARCHAR} /if if testplaceEntity ! null and placeEntity.placeId ! null and placeEntity.placeId ! AND ST.PLACE_ID #{placeEntity.placeId, jdbcTypeVARCHAR} /if if teststudentId ! null and studentId ! AND ST.STUDENT_ID #{studentId, jdbcTypeVARCHAR} /if /trim /selecttrim代替set!-- 5.2 if/trim代替set(判断参数) - 将实体类不为空的属性更新 -- update idupdateStudent_if_trim parameterTypeliming.student.manager.data.model.StudentEntity UPDATE STUDENT_TBL trim prefixSET suffixOverrides, if teststudentName ! null and studentName ! STUDENT_TBL.STUDENT_NAME #{studentName}, /if if teststudentSex ! null and studentSex ! STUDENT_TBL.STUDENT_SEX #{studentSex}, /if if teststudentBirthday ! null STUDENT_TBL.STUDENT_BIRTHDAY #{studentBirthday}, /if if teststudentPhoto ! null STUDENT_TBL.STUDENT_PHOTO #{studentPhoto, javaTypebyte[], jdbcTypeBLOB, typeHandlerorg.apache.ibatis.type.BlobTypeHandler}, /if if testclassId ! STUDENT_TBL.CLASS_ID #{classId}, /if if testplaceId ! STUDENT_TBL.PLACE_ID #{placeId} /if /trim WHERE STUDENT_TBL.STUDENT_ID #{studentId} /update9、foreach对于动态SQL 非常必须的主是要迭代一个集合通常是用于IN 条件。List 实例将使用“list”做为键数组实例以“array” 做为键。foreach元素是非常强大的它允许你指定一个集合声明集合项和索引变量它们可以用在元素体内。它也允许你指定开放和关闭的字符串在迭代之间放置分隔符。这个元素是很智能的它不会偶然地附加多余的分隔符。注意你可以传递一个List实例或者数组作为参数对象传给MyBatis。当你这么做的时候MyBatis会自动将它包装在一个Map中用名称在作为键。List实例将会以“list”作为键而数组实例将会以“array”作为键。这个部分是对关于XML配置文件和XML映射文件的而讨论的。下一部分将详细讨论Java API所以你可以得到你已经创建的最有效的映射。参数为array示例的写法接口的方法声明public ListStudentEntity getStudentListByClassIds_foreach_array(String[] classIds);动态SQL语句!-- 7.1 foreach(循环array参数) - 作为where中in的条件 -- select idgetStudentListByClassIds_foreach_array resultMapresultMap_studentEntity SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST WHERE ST.CLASS_ID IN foreach collectionarray itemclassIds open( separator, close) #{classIds} /foreach /select测试代码查询学生中在20000001、20000002这两个班级的学生Test public void test7_foreach() { String[] classIds { 20000001, 20000002 }; ListStudentEntity list this.dynamicSqlMapper.getStudentListByClassIds_foreach_array(classIds); for (StudentEntity e : list) { System.out.println(e.toString()); } }参数为list示例的写法接口的方法声明public ListStudentEntity getStudentListByClassIds_foreach_list(ListString classIdList);动态SQL语句!-- 7.2 foreach(循环ListString参数) - 作为where中in的条件 -- select idgetStudentListByClassIds_foreach_list resultMapresultMap_studentEntity SELECT ST.STUDENT_ID, ST.STUDENT_NAME, ST.STUDENT_SEX, ST.STUDENT_BIRTHDAY, ST.STUDENT_PHOTO, ST.CLASS_ID, ST.PLACE_ID FROM STUDENT_TBL ST WHERE ST.CLASS_ID IN foreach collectionlist itemclassIdList open( separator, close) #{classIdList} /foreach /select测试代码查询学生中在20000001、20000002这两个班级的学生Test public void test7_2_foreach() { ArrayListString classIdList new ArrayListString(); classIdList.add(20000001); classIdList.add(20000002); ListStudentEntity list this.dynamicSqlMapper.getStudentListByClassIds_foreach_list(classIdList); for (StudentEntity e : list) { System.out.println(e.toString()); } }sql片段标签sql通过该标签可定义能复用的sql语句片段在执行sql语句标签中直接引用即可。这样既可以提高编码效率还能有效简化代码提高可读性需要配置的属性id 表示需要改sql语句片段的唯一标识引用通过include refid /标签引用refid 中的值指向需要引用的sql中的id“”属性!--定义sql片段-- sql idorderAndItem o.order_id,o.cid,o.address,o.create_date,o.orderitem_id,i.orderitem_id,i.product_id,i.count /sql select idfindOrderAndItemsByOid parameterTypejava.lang.String resultMapBaseResultMap select !--引用sql片段-- include refidorderAndItem / from ordertable o join orderitem i on o.orderitem_id i.orderitem_id where o.order_id #{orderId} /select