1. 程式人生 > 實用技巧 >9.1 多對一需求程式碼編寫

9.1 多對一需求程式碼編寫

9.1 多對一需求程式碼編寫

需求:查詢所有學生資訊,以及對應的老師資訊

方法一:按照查詢巢狀處理(子查詢)

  • sql語句:select s.id,s.name,t.id from student s where t.id=(select id from teacher )

第一步:編寫mapper介面

public interface StudentMapper {

//需求:查詢所有學生資訊,以及對應的老師資訊
List<Student> findAllStudents()throws Exception;
}
public interface TeacherMapper {

Teacher findTeacherById(Integer id)throws Exception;
}

第二步:編寫StudentMapper.xml配置檔案(關鍵)

  • 關鍵一:我們需要先查出學生表的所有資訊

  • 關鍵二:通過id查出教師表的相應資訊,因為我們學生實體類是關聯到教師類的

  • 關鍵三:通過ResultMap做對映處理 前兩個欄位就正常寫,複雜屬性通過官網我們知道要使用association標籤,需要制定型別以及sql語句 也可以說是套娃學生sql套teacher的sql

<?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">
<!--namespace名稱空間-->
<mapper namespace="com.xuan.mapper.StudentMapper">

<resultMap id="studentMap" type="Student">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<!--複雜屬性我們不用result-->
<association property="teacher" column="tid" javaType="Teacher" select="findTeacherById" ></association>
</resultMap>

<select id="findAllStudents" resultMap="studentMap">
select * from student
</select>

<select id="findTeacherById" parameterType="int" resultType="Teacher">
select * from teacher where id =#{id}
</select>
</mapper>

第三步:編寫測試

@Test
public void testFindAllStudents() throws Exception {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

List<Student> students = mapper.findAllStudents();
for (Student student : students) {
System.out.println(student);
}

sqlSession.close();
}

---------------------------------------測試成功-----------------------------------------

方法二: 按照結果巢狀處理(聯表查詢)

  • sql語句 select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id

  • 其他都與按照查詢巢狀處理方式一致,這裡就寫關鍵處

  • 編寫StudentMapper.xml配置檔案

<resultMap id="studentMap" type="Student">
<result property="id" column="sid"></result>
<result property="name" column="sname"></result>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"></result>
</association>
</resultMap>

<select id="findAllStudents" resultMap="studentMap">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id
</select>