栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis中Collection集合标签的使用详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis中Collection集合标签的使用详解

mybatis简单的CURD就不用多说了,网上相关博客文档一大堆。分析一下Mybatis里面的collection聚集查询。
假设一个班级有多名学生为例,通过班级号查询出该班级的信息,和班级里面的所有学生的信息,一般的做法就是通过班级号把班级的信息查询出来,再通过班级ID号把该班级里面的所有学生查询出来,我们不用这种通用的方法

1.班级实体类可以定义为这样:

import java.util.List;

public class ClazzEntity {

  private int clazzID;

  private String clazzName;

  private List 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 getStudentList() {
    return studentList;
  }

  public void setStudentList(List studentList) {
    this.studentList = studentList;
  }
}

学生实体类定义:

package com.cn.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配置文件如下所示:





 
  
  
  
 

  
   
   
   
  
  


  select stuID,stuName,stuAge,stuAddress,classID
  from student_t
  where classID = #{clazzID}


这样就可以查到一个班级的信息,和班级里面的所有学生信息:

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集合标签内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/133731.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号