标签:
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);
public class Teacher {
private int id;
private String name;
}
public class Classes {
private int id;
private String name;
private Teacher teacher;
}
<!-- 方式一:嵌套结果 -->
<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();
}
<!-- 方式:嵌套查询:本质是二次查询 -->
<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();
}
标签:
原文地址:http://www.cnblogs.com/mentorStudio/p/4809622.html