示例【通过班级查询学生信息】
t_student表
t_classes表
创建Student
package com.po;
public class Student {
private Integer sid; //学号
private String sname; //姓名
private String sex; //性别
private String address; //地址
private Integer cId; //班级id
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getcId() {
return cId;
}
public void setcId(Integer cId) {
this.cId = cId;
}
@Override
public String toString() {
return "Student [sid=" + sid + ", sname=" + sname
+ "]";
}
}
创建Classes
package com.po;
import java.util.List;
public class Classes {
private Integer cId;
private String cName;
private List<Student> students;
public Integer getcId() {
return cId;
}
public void setcId(Integer cId) {
this.cId = cId;
}
public String getcName() {
return cName;
}
public void setcName(String cName) {
this.cName = cName;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "Classes [cId=" + cId + ", cName=" + cName + ", students=" + students + "]";
}
}
创建ClassesDao
package com.dao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.factory.SessionFactory;
import com.po.Classes;
public class ClassesDao {
private SqlSession session=SessionFactory.getSqlSession();
@Test
public void findStudentByCid() {
Classes classess=session.selectOne("com.mapper.ClassesMapper.findStudentByCid", 2);
System.out.println(classess);
}
}
创建ClassesMapper.xml
<?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="com.mapper.ClassesMapper">
<resultMap type="com.po.Classes" id="ClassesWithStudent">
<id property="cId" column="cId"/>
<result property="cName" column="cName"/>
<collection property="students" ofType="com.po.Student">
<id property="sid" column="sid"/>
<result property="sname" column="sname"/>
<result property="sex" column="sex"/>
<result property="address" column="address"/>
<result property="cId" column="cId"/>
</collection>
</resultMap>
<select id="findStudentByCid" parameterType="Integer" resultMap="ClassesWithStudent">
select s.sid,s.sname,c.cId,c.cName from t_student s,t_classes c where s.cId=c.cId
and c.cId=#{cId}
</select>
</mapper>
配置mybatis-config.xml
<!-- 配置Mapper的位置 -->
<mappers>
<mapper resource="com/mapper/ClassesMapper.xml"/>
</mappers>
执行findStudentByCid()方法