1.创建一个用来关联的表
2.创建外键约束
3.查询
SELECT s.id id, s.name name, s.sex sex, s.age age, s.grade_id grade_id, g.id gid, g.grade_name grade_name FROM student s, grade g WHERE s.grade_id=g.id AND s.name='skye'
在web中
StudentMapper.class
//利用关联查询的方法从数据库获取学生的信息以及班级信息 public Students getStuAndGrade(Integer id);
StudentMapper.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.dao.StudentMapperPlus"> <!--public Students getStuAndGrade(Integer id);--> <resultMap type="com.person.Students" id="myStu"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="sex" property="sex"/> <result column="age" property="age"/> <result column="gid" property="grade.id"/> <result column="grade_name" property="grade.gradeName"/> </resultMap> <select id="getStuAndGrade" resultMap="myStu"> SELECT s.id id, s.name name, s.sex sex, s.age age, s.grade_id grade_id, g.id gid, g.grade_name grade_name FROM student s, grade g WHERE s.grade_id=g.id AND s.id=#{id} </select> </mapper>
Test
@Test public void test5() throws IOException { String resource ="conf/com/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession openSession = sqlSessionFactory.openSession(); try{ StudentMapperPlus mapper = openSession.getMapper( StudentMapperPlus.class ); Students students = mapper.getStuAndGrade(1); System.out.println(students); }finally{ openSession.close(); } }
使用association的StudentMapper.xml 其余不变
<!-- 使用association定义关联的单个对象的封装规则; --> <resultMap type="com.person.Students" id="myStu1"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="sex" property="sex"/> <result column="age" property="age"/> <!-- association可以指定联合的javaBean对象 property="grade":指定哪个属性是联合的对象 javaType:指定这个属性对象的类型[不能省略] --> <association property="grade" javaType="com.person.Grade"> <id column="gid" property="id"/> <result column="grade_name" property="gradeName"/> </association> </resultMap> <select id="getStuAndGrade" resultMap="myStu1"> SELECT s.id id, s.name name, s.sex sex, s.age age, s.grade_id grade_id, g.id gid, g.grade_name grade_name FROM student s, grade g WHERE s.grade_id=g.id AND s.id=#{id} </select>