1 需求
- 一个老师对应一个班级
- 一个班级只有一个老师
- 根据班级id查询班级信息,这个班级信息中有老师的信息
2 创建表和数据
CREATE TABLE teacher(
t_id INT PRIMARY KEY AUTO_INCREMENT,
t_name VARCHAR(20)
);
CREATE TABLE class(
c_id INT PRIMARY KEY AUTO_INCREMENT,
c_name VARCHAR(20),
teacher_id INT
);
//在班级表中加一个外键,指向老师表的主键
ALTER TABLE class ADD CONSTRAINT fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teacher(t_id);
INSERT INTO teacher(t_name) VALUES(‘LS1‘);
INSERT INTO teacher(t_name) VALUES(‘LS2‘);
INSERT INTO class(c_name, teacher_id) VALUES(‘bj_a‘, 1);
INSERT INTO class(c_name, teacher_id) VALUES(‘bj_b‘, 2);
3 定义实体类
3.1 Teacher
public class Teacher {
private int id;
private String name;
}
3.2 Classes
public class Classes {
private int id;
private String name;
private Teacher teacher;
}
4 定义映射文件 classMapper.xml
4.1方式一:嵌套结果,使用嵌套结果映射来处理重复的联合结果的子集, 封装联表查询的数据(去除重复的数据)
- xml
<!-- 方式一:嵌套结果 -->
<resultMap type="Classes" id="ClassResultMap">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" javaType="Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
</association>
</resultMap>
<select id="getClass" parameterType="int" resultMap="ClassResultMap">
select * from class c, teacher t where c.teacher_id=t.t_id and c.c_id=#{id}
</select>
- 测试
@Test
public void test1(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession();
String statement = "cn.imentors.mybatis.test5.classMapper.getClass";
Classes c = session.selectOne(statement , 2);
System.out.println(c);
session.close();
}
4.2 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型
- xml
<!-- 方式:嵌套查询:本质是二次查询 -->
<select id="getClass2" parameterType="int" resultMap="ClassResultMap2">
select * from class where c_id=#{id}
</select>
<resultMap type="Classes" id="ClassResultMap2">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<!-- column:是classes表中外键字段 -->
<association property="teacher" column="teacher_id" select="getTeacher">
</association>
</resultMap>
<select id="getTeacher" parameterType="int" resultType="Teacher">
SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
</select>
测试
@Test
public void test2(){
SqlSessionFactory factory = MybatisUtils.getFactory();
SqlSession session = factory.openSession();
String statement = "cn.imentors.mybatis.test5.classMapper.getClass2";
Classes c = session.selectOne(statement , 2);
System.out.println(c);
session.close();
}
5 属性值说明
- association:用于一对一的关联查询
- property:对象属性名称
- javaType:对象属性的类型
- column:表的字段名称
- select:使用另一个查询封闭的结果
捐赠我们
良师益友工作室一直在致力于帮助编程爱好更加快速方便地学习编程,如果您对我们的成果表示认同并且觉得对你有所帮助,欢迎您对我们捐赠^_^。
时间: 2024-10-13 22:04:22