mybatis的collection用法
mybatis中foreach_collection用法_范文模板及概述

mybatis中foreach collection用法范文模板及概述1. 引言概述:在使用Mybatis进行数据库操作时,我们经常会遇到需要对一个集合进行循环遍历的情况。
而Mybatis提供了foreach collection语法来实现这种需求。
通过foreach collection语句,我们可以快速、便捷地在SQL语句中引用一个集合,并遍历其中的元素。
文章结构:本文将详细介绍Mybatis中foreach collection的用法及相关注意事项。
首先,我们将给出该语句的基本作用和语法,并解释collection参数的使用方式以及它所代表的含义。
接着,我们将详细解析foreach元素内部可用的属性,帮助读者更好地理解并灵活运用该语法。
然后,我们通过示例与范文模板来展示foreach collection的不同应用场景,并介绍如何动态拼接SQL语句以及如何利用对象集合进行批量操作。
最后,我们会列举一些注意事项和常见问题解答,包括如何处理空指针异常、数据库特殊字符转义以及循环嵌套时对应关系处理技巧等方面。
最后,在结论部分总结全文内容。
目的:本文的目的是让读者能够充分理解并掌握Mybatis中foreach collection语句的使用方法,以及在实际开发中如何应用该语法解决常见问题。
通过该文,读者将对foreach collection有更深入的认识,并能够熟练运用它来提升自己的数据库操作效率和灵活性。
2. Mybatis中foreach collection用法2.1 foreach语句的作用与基本语法Mybatis中的foreach语句用于循环遍历一个集合,并将其中的元素作为参数传递给SQL语句中的占位符。
它常用于批量操作或动态生成SQL语句。
在Mybatis中,使用foreach语句的基本语法如下:```xml<foreach item="item" collection="collection" open="(" close=")" separator=",">#{item}</foreach>```其中,以下是各个属性的含义:- `item`:指定集合中每个元素在循环过程中对应的名称。
mybatis collection column 方法

mybatis collection column 方法1. 引言1.1 概述在此章节中,我们将讨论有关MyBatis的Collection Column方法。
MyBatis 是Java中一个非常流行和强大的持久层框架,它提供了许多便利的功能来简化数据库访问。
其中,Collection Column方法是MyBatis中一个重要的特性,可以用来处理数据库中的集合列数据。
1.2 文章结构本文将按照以下结构进行介绍和分析:首先,在第二部分我们将详细介绍Collection Column方法的概念和作用;然后,在第三部分我们将讨论Collection列的配置方式,并提供一些示例来帮助读者更好地理解其使用方法;最后,在结论部分我们将对MyBatis Collection Column方法进行总结评价,并展望其未来发展方向。
1.3 目的本文的目的在于帮助读者全面了解和掌握MyBatis Collection Column方法。
通过学习本文,读者将能够清楚地了解该方法在实际项目开发中的应用场景,并能够准确配置和使用Collection列以处理各种集合数据类型。
同时,本文也旨在为读者提供对该特性进行评价和展望未来发展方向。
请注意,本文章为长文,请按照目录结构进行逐步撰写相关内容。
如有需要,请随时提问。
2. MyBatis Collection Column 方法2.1 介绍Collection Column方法:MyBatis是一款优秀的持久层框架,提供了丰富的查询方式和支持。
其中,Collection Column方法是MyBatis提供的一种特殊方法,用于处理数据库表中的集合类型字段。
Collection Column方法的作用是将关联表中的多个记录根据某个字段进行归纳,并以集合形式存储在主表中的一个列中。
这样,在主表查询时,可以直接获取到与之关联的多个子记录。
2.2 Collection列配置方式:在MyBatis中配置Collection列主要分为两步:定义映射关系和设置映射结果。
mybatis查询优化主子表查询之association和collection

mybatis查询优化主⼦表查询之association和collection很多开发⼈员之所以编写出低效的应⽤,有⼀⼤原因是并不理解怎样编写⾼效的SQL。
以订单查询为例,我们经常需要查询某个⽤户的订单以及订单明细,并且以树形⽅式展现如下:对于这种性质的功能,很多开发⼈员的做法是先查询主表,然后根据主表去循环⼦表,如下所⽰:List<Department> depts = DepartmentMapper.queryDept();for (Department dept: depts) {dept.setEmps(EmployeeMapper.queryEmp(dept.id));}这种做法就是典型的过程性编程思维,它不仅在更改查询条件或字段时维护性差、不⽀持两个表的查询条件,⽽且性能低下,主表有⼏条记录就会导致请求数据库⼏次,不仅应⽤响应时间长,服务器也耗费了更多的资源。
更好的做法是⼀次性查询会所有符合条件的记录,然后再应⽤中进⾏拆分并组装,主流的ORM框架⼏乎都⽀持这些模式,以使⽤最⼴泛的Mybatis为例,其结果映射resultMap中的association(⽤于⼀对⼀和多对⼀)和collection(⽤于⼀对多)元素⽀持⾃动将⼆位结果映射为主⼦对象。
如下所⽰:<mapper namespace="chapter6.dao.DepartmentMapper"><!-- 嵌套结果集的⽅式,使⽤collection标签定义关联的集合类型的属性封装规则 --><resultMap type="chapter6.Department" id="MyDept"><id column="did" property="id"/><result column="dept_name" property="departmentName"/><collection property="emps" ofType="chapter6.Employee"><id column="eid" property="id"/><result column="last_name" property="lastName"/><result column="email" property="email"/><result column="gender" property="gender"/></collection></resultMap><select id="queryDept" resultMap="MyDept">SELECTd.id did,d.dept_name dept_name,e.id,st_name last_name,e.email email,e.gender genderFROMtbl_dept dLEFT JOIN tbl_employee e ON d.id = e.d_id</select></mapper>association同样可以实现相同功能,不过明细表是主表,如下所⽰:<mapper namespace="com.abc.mapper.StudentMapper"><select id="getById" parameterType="int"resultMap="studentResultMap">select s.id s_id, s_name,s.gender s_gender,s.major s_major,s.grade s_grade,t.id t_id, t_name,t.gender t_gender,t.title t_title,t.research_area t_research_areafrom student s left join teacher ton s.supervisor_id = t.idwhere s.id=#{id}</select><resultMap id="studentResultMap" type="Student"><id property="id" column="s_id"/><result property="name" column="s_name"/><result property="gender" column="s_gender"/><result property="major" column="s_major"/><result property="grade" column="s_grade"/><!--使⽤resultMap属性引⽤下⾯的教师实体映射 --><association property="supervisor" javaType="Teacher"resultMap="supervisorResultMap"/></resultMap><!--教师实体映射 --><resultMap id="supervisorResultMap" type="Teacher"><id property="id" column="t_id"/><result property="name" column="t_name"/><result property="gender" column="t_gender"/><result property="researchArea" column="t_research_area"/><result property="title" column="t_title"/></resultMap></mapper>需要注意的是,默认情况下Mapper中使⽤association标签,select 有⼤量相同的数据,此时会出现问题,有的数据可以联查出来,⽽有的不可以。
Mybatis之collection标签嵌套查询(select)的写法

Mybatis之collection标签嵌套查询(select)的写法业务:查询⼀种商品,展⽰该商品多种规格。
GroupDetailsVo :package munity.api.vo;import java.io.Serializable;import java.math.BigDecimal;import java.util.Date;import java.util.List;import lombok.Data;/*** 团购详情vo** @author admin* @date 2019 -11-20 15:29:51*/@Datapublic class GroupDetailsVo implements Serializable{private Long groupById;/*** 团购状态 2:未开始 3:团购中 4:已结束*/private Byte groupBuyStatus;/*** 主图*/private String mainPicture;/*** 商品名称*/private String name;/*** 详情*/private String content;/*** 配送⽅式 1:⾃提 2:上门*/private String deliveryType;/***满额免费配送*/private BigDecimal freeDeliveryPrice;/***已卖总数量*/private Integer sellNumber;/*** 原价*/private BigDecimal originalPrice;/*** 团购价*/private BigDecimal groupByPrice;/*** 开始时间*/private Date startTime;/**** 结束时间*/private Date endTime;/*** 单、多规格详情vo*/private List<StandardDetailsVo> standardDetailsVos;}StandardDetailsVo :package munity.api.vo;import java.io.Serializable;import lombok.Data;/*** 单、多规格详情vo** @author admin* @date 2019 -11-25 09:36:39*/@Datapublic class StandardDetailsVo implements Serializable{/*** 规格id*/private Long standardId;/*** 规格名称*/private String standardName;}接⼝名:/*** 获取团购详情* @param groupBuyId* @return* @author admin* @date 2019 -11-21 17:05:20*/List<GroupDetailsVo> getGroupDetails (@Param("groupBuyId")Long groupBuyId);mapper://collection标签内的select为本mapper内的⽅法名、column为查询条件的列名、property为实体类List名字,见上⾯实体类<单、多规格详情vo>字段名字。
mybatis中的collection用法

在 MyBatis 中,<collection>元素用于处理关联关系中的一对多(one-to-many)或多对多(many-to-many)的映射。
它允许你在查询结果中包含集合(List、Set 或Map)类型的属性。
以下是<collection>元素的基本用法:
一对多关系映射:
考虑两个实体类Author和Article,一个作者可以有多篇文章:
1. 数据库表结构:
2. MyBatis 映射文件:
在上述示例中,通过<collection>元素,我们将Author实体类中的articles属性与Article实体类建立了一对多的关系。
多对多关系映射:
如果有两个实体类Student和Course,一个学生可以选择多门课程,一门课程也可以被多个学生选择。
这是一个典型的多对多关系:
1. 数据库表结构:
2. MyBatis 映射文件:
在上述示例中,通过<collection>元素,我们将Student实体类中的courses属性与Course实体类建立了多对多的关系。
关联关系的维护通常需要在数据库中的中间表中进行,这里的中间表是student_course。
Mybatis中Collection集合标签的使用详解

Mybatis中Collection集合标签的使⽤详解mybatis简单的CURD就不⽤多说了,⽹上相关博客⽂档⼀⼤堆。
分析⼀下Mybatis⾥⾯的collection聚集查询。
假设⼀个班级有多名学⽣为例,通过班级号查询出该班级的信息,和班级⾥⾯的所有学⽣的信息,⼀般的做法就是通过班级号把班级的信息查询出来,再通过班级ID号把该班级⾥⾯的所有学⽣查询出来,我们不⽤这种通⽤的⽅法1.班级实体类可以定义为这样:import java.util.List;public class ClazzEntity {private int clazzID;private String clazzName;private List<StudentEntity> studentList;public int getClassID() {return clazzID;}public int getClazzID() {return clazzID;}public void setClazzID(int clazzID) {this.clazzID = clazzID;}public String getClazzName() {return clazzName;}public void setClazzName(String clazzName) {this.clazzName = clazzName;}public List<StudentEntity> getStudentList() {return studentList;}public void setStudentList(List<StudentEntity> studentList) {this.studentList = studentList;}}学⽣实体类定义:package .hnust.pojo;public class StudentEntity {private int stuID;private String stuName;private int stuAge;private String stuAddress;public int getStuID() {return stuID;}public void setStuID(int stuID) {this.stuID = stuID;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}public int getStuAge() {return stuAge;}public void setStuAge(int stuAge) {this.stuAge = stuAge;}public String getStuAddress() {return stuAddress;}public void setStuAddress(String stuAddress) {this.stuAddress = stuAddress;}}2.数据库建表语句:CREATE TABLE student_t(stuno INT PRIMARY KEY,stuname VARCHAR(20),stuage INT,stuaddress VARCHAR(20) ,classid INT);CREATE TABLE class_t(classid INT PRIMARY KEY,classname VARCHAR(20));3.查询ClazzEntity中的学⽣信息列表StudentEntity,通过mybatis中的collection标签来配置,其中,ofType是查询返回的学⽣信息对应的实体类,select为要执⾏的查询学⽣列表的查询语句,mybatis的xml配置⽂件如下所⽰:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd" ><mapper namespace="ManageDao" ><resultMap id="ClazzResultMap" type=".hnust.pojo.ClazzEntity" ><id column="classID" property="clazzID" jdbcType="INTEGER" /><result column="className" property="clazzName" jdbcType="VARCHAR" /><collection property="studentList" column="classID" javaType="ArrayList"ofType=".hnust.pojo.StudentEntity" select="getStudentByClassID"/></resultMap><resultMap id="StudentResultMap" type=".hnust.pojo.StudentEntity"><id property="stuID" column="stuID" /><result property="stuName" column="stuName" /><result property="stuAge" column="stuAge" /><result property="stuAddress" column="stuAddress" /></resultMap><select id="getClassByID" resultMap="ClazzResultMap" parameterType="ng.Integer" >select classID,classNamefrom class_twhere classID = #{clazzID}</select><select id="getStudentByClassID" resultMap="StudentResultMap" parameterType="ng.Integer" >select stuID,stuName,stuAge,stuAddress,classIDfrom student_twhere classID = #{clazzID}</select></mapper>这样就可以查到⼀个班级的信息,和班级⾥⾯的所有学⽣信息:ClazzEntity [clazzID=1, clazzName=junior, studentList=[StudentEntity [stuID=1001, stuName=wanghai,stuAge=18, stuAddress=beijing], StudentEntity [stuID=1002, stuName=zhangdong, stuAge=20,stuAddress=shanghai]]]到此这篇关于Mybatis中Collection集合标签的使⽤详解的⽂章就介绍到这了,更多相关Mybatis中Collection集合标签内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
mybatis中foreachcollection的三种用法

mybatis中foreachcollection的三种⽤法foreach元素的属性主要有 item,index,collection,open,separator,close。
1. item表⽰集合中每⼀个元素进⾏迭代时的别名,2. index指定⼀个名字,⽤于表⽰在迭代过程中,每次迭代到的位置,3. open表⽰该语句以什么开始,4. separator表⽰在每次进⾏迭代之间以什么符号作为分隔符,5. close表⽰以什么结束。
collection是这⾥⾯⽐较难得下⾯我们详细介绍⼀下实际中的运⽤:1. 如果传⼊的是单参数且参数类型是⼀个List的时候,collection属性值为list2. 如果传⼊的是单参数且参数类型是⼀个array数组的时候,collection的属性值为array3. 如果传⼊的参数是多个的时候,我们就需要把它们封装成⼀个Map了,当然单参数也可4. 如果传⼊的参数是多个的时候,我们也可以放在实体类中(这种实际⽤到也是⾮常多的)下⾯详细介绍这⼏种⽅法:1.1.<select id="queryUser" resultType="erEntity">2.select * from tab_user where user_id in3.<foreach collection="list" item="item" open="(" separator="," close=")" index="index">4.#{item}5.</foreach>6.</select>1./**2.* 根据传⼊的id获取对应的user3.* @param ids4.* @return5.*/6.List<UserEntity> queryUser(List<String> ids);2.1.<delete id="deleteUserById" >2.delete from tab_user where user_id in3.<foreach collection="array" item="item" open="(" separator="," close=")" index="index">4.#{item}5.</foreach>6.</delete>1./**2.* 根据传⼊的ID删除对应的⽤户3.* @param ids4.* @return5.*/6.int deleteUserById (String[] ids);3.1.<select id="queryUserByUser" parameterType="java.util.Map" resultType="erEntity"> 2.select * from tab_user where user_name = #{name} and user_id in3.<foreach collection="ids" item="item" open="(" separator="," close=")" index="index">4.#{item}5.</foreach>6.</select>1./**2.* 根据Map中的信息获取对应的⽤户3.* @param user4.* @return5.*/6.List<UserEntity> queryUserByUser(Map user);4.1.<insert id="addUsers" parameterType="erEntity" >2.insert into tab_user (user_id,user_name) values3.<foreach collection="userId.split(',')" item="item" separator=",">4.(#{item},#{userName})5.</foreach>6.</insert>1./**2.* 根据传⼊的user添加⽤户多个userId⽤逗号隔开3.* @param user4.* @return5.*/6.int addUsers(UserEntity user);下⾯有附上完整的代码:1.<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd">3.4.<mapper namespace="erMapper">5.6.<select id="queryUser" resultType="erEntity">7.select * from tab_user where user_id in8.<foreach collection="list" item="item" open="(" separator="," close=")" index="index">9.#{item}10.</foreach>11.12.</select>13.14.<delete id="deleteUserById" >15.delete from tab_user where user_id in16.<foreach collection="array" item="item" open="(" separator="," close=")" index="index">17.#{item}18.</foreach>19.</delete>20.21.<select id="queryUserByUser" parameterType="java.util.Map" resultType="erEntity"> 22.select * from tab_user where user_name = #{name} and user_id in23.<foreach collection="ids" item="item" open="(" separator="," close=")" index="index">24.#{item}25.</foreach>26.</select>27.28.<insert id="addUsers" parameterType="erEntity" >29.insert into tab_user (user_id,user_name) values30.<foreach collection="userId.split(',')" item="item" separator=",">31.(#{item},#{userName})32.</foreach>33.</insert>34.</mapper>package com.example.demo.mapper;2.3.4.import erEntity;5.6.import java.util.List;7.import java.util.Map;8.9./**10.* @author pidaowei11.*/12.public interface UserMapper {13.14./**15.* 根据传⼊的id获取对应的user16.* @param ids17.* @return18.*/19.List<UserEntity> queryUser(List<String> ids);20.21./**22.* 根据传⼊的ID删除对应的⽤户23.* @param ids24.* @return25.*/26.int deleteUserById (String[] ids);27.28./**29.* 根据Map中的信息获取对应的⽤户30.* @param user31.* @return32.*/33.List<UserEntity> queryUserByUser(Map user);34./**36.* 根据传⼊的user添加⽤户多个userId⽤逗号隔开37.* @param user38.* @return39.*/40.int addUsers(UserEntity user);41.42.}1.package com.example.demo.entity;2.import lombok.Data;3./**4.* @author pidaowei5.*/6.@Data7.public class UserEntity {8.9.private String userId;10.private String userName;11.}12.。
mybatiscollection一对多关联查询,单边分页的问题总结!

mybatiscollection⼀对多关联查询,单边分页的问题总结!若想直接通过sql实现多级关联查询表结构得有2 个必不可少的字段:id ,parentId,levelIdid:主键id,parentId:⽗idlevelId:表⽰第⼏级(表本⾝关联查询的时候需要⽤到,不然会有重复数据)利⽤mybatis collection 实现⼀对多关联查询Dto:(⼀级)public class ProvinceInfoDTO implements Serializable {private String id;private String name;private String pinyin;private String firstLetter;private List<CitysInfoDTO> cities;}Dto:(⼆级)public class CitysInfoDTO implements Serializable {private String id;private String name;private String pinyin;private String firstLetter;private String acronym;private List<RegionInfoDTO> regions;}Dto(三级)public class RegionInfoDTO implements Serializable {private String id;private String name;private String pinyin;private String firstLetter;}resultMap<resultMap id="unloadAreaQueryResultMap" type="com.haoyunhu.res.ProvinceInfoDTO"> // ⼀级<result column="aid" property="id"/><result column="aname" property="name"/><result column="apinyin" property="pinyin"/><result column="aletter" property="firstLetter"/><collection property="cities" ofType="com.haoyunhu.res.CitysInfoDTO"> //⼆级<result column="bid" property="id"/><result column="bname" property="name"/><result column="bpinyin" property="pinyin"/><result column="bletter" property="firstLetter"/><result column="bacronym" property="acronym"/><collection property="regions" ofType="com.haoyunhu.res.RegionInfoDTO"> // 三级<result column="cid" property="id"/><result column="cname" property="name"/><result column="cpinyin" property="pinyin"/><result column="cletter" property="firstLetter"/></collection></collection></resultMap>省市区级联查询sql:SELECT a.PROV_NAME,b.PROV_NAME,c.PROV_NAMEFROM T_DATA_AREAS aLEFT JOIN T_DATA_AREAS bON a.id=b.PROV_PARENTIDLEFT JOIN T_DATA_AREAS CON b.id =C.PROV_PARENTIDWHERE a.PROV_LEVELTYPE=1AND b.PROV_LEVELTYPE =2AND c.PROV_LEVELTYPE =3ORDER BY a.PROV_NAME;以上mybatis的操作最终得到的json是:{"id":"310000","name":"上海","pinyin":"Shanghai","firstLetter":"","cities":[{"id":"310100","name":"上海市","pinyin":"Shanghai","firstLetter":"","acronym":"","regions":[{"id":"230506","name":"宝⼭区","pinyin":"Baoshan","firstLetter":""}]}]}⼀对多关联查询单边分页:上述的这种关联查询时没法直接使⽤pagehelper分页插件的,因为pagehelper分页插件是针对真个sql 截取,所以只能⼿动分页(简单,分页⽆⾮就是截取sql +查询总条数),所以若⼀对多关联查询想分页得针对主表(案例中的A表)截取sql(pageindex pagesize) ,再另外写条sql查询主表(案例中的A表)的记录数 ------注意mysql 的偏移量的概念还需要注意的坑:1:这种需要做级联查询,表结构⼜不满⾜的坑:若表结构不满⾜,但是⼜想省事,就得写sql 把原表整成这种固定格式的临时表结构(⼦查询)2:电商领域的商品类⽬的级联查询和这个省市区的查询⼀样(都需要levelid,⽤在查询条件处:where a.levelid=0 and b.levelid=1 and c.levelid=2;当然这种级联查询可以在java代码中可以实现,三条sql,分别查询 level =0 1 2的,然后java代码⾥⾯循环!。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
mybatis的collection用法
Mybatis在处理关联表时非常好用的一种语法是Collection,使得查询起来更加方便。
Collection的应用非常广泛,比如一个表mainTable与表subTable存在一对多的关系,Mybatis可以用Collection语法以比较简单的方式得到查询结果。
使用Collection的步骤如下:
1、编写SQL,把主表的实体与子表的实体混合在一起,使用连接子句,然后返回主表的所有字段,以及子表想要得到的字段
2、编写与主表一一对应的Mapper
3、在mainTableMapper中声明一个collection,该collection 指向子表的mapper
4、在mybatis的配置文件中配置上述collection
5、在主表中通过主键字段作为循环结构,通过collection来存放子表查询结果
联接表查询是Mybatis最常用的技术之一。
Collection语法可以让我们在SQL语句中更加灵活地处理数据,而且查询效率非常高。
Mybatis的collection语法能够让我们用一句SQL实现更多的功能,比如从一张表中得到多条数据记录,或者从两张表联接查询重组以供使用。
当我们不得不查询比较复杂的表时,Mybatis的
collection是非常受用的,它可以减少我们的编码工作量,并且让查询更加规范。