mybatis复杂查询环境 多对一的处理 按照结果嵌套处理和按照查询嵌套处理
生活随笔
收集整理的這篇文章主要介紹了
mybatis复杂查询环境 多对一的处理 按照结果嵌套处理和按照查询嵌套处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
sql插入表student的語句:
insert into student (id, name, tid) values ('9', '梁梁','2'); insert into student (id, name,tid) values ('7', '亮亮','2');兩張表:
所對應的實體類,學術類:
老師:
package com.kuang.pojo;import lombok.Data;import java.util.List;@Data public class Teacher {private int id;private String name; private List<Student>stus;//一個老師關聯多個學生 }多對一查詢語句:
sql編輯器下面輸入:
顯示:
嵌套查詢:
按照查詢嵌套處理
目錄:
查詢所有的學生信息
根據查詢出來的學生tid,尋找對應的老師,子查詢:
復雜的屬性,我們需要單獨處理,對象:association,集合:collection
測試類:
注意,type要用全類名,不然會報錯
按照結果嵌套處理
測試類:
@Testpublic void testStudent(){SqlSession sqlSession = MybatisUtils.getSqlSession();Studenmapper stuma = sqlSession.getMapper(Studenmapper.class);List<Student> stu = stuma.getstudent2();for(Student stu1:stu){System.out.println(stu1);}sqlSession.close();}Studenmapper:
package com.kuang.dao; import com.kuang.pojo.Student;import java.util.List;public interface Studenmapper {public List<Student>getstudent();public List<Student>getstudent2(); }xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.kuang.dao.Studenmapper"> <select id="getstudent2" resultMap="StudenTeacher2">select s.id sid,s.name sname,t.name tnamefrom student s,teacher twhere s.tid=t.id; </select><resultMap id="StudenTeacher2" type="com.kuang.pojo.Student"><result property="id" column="sid"/><result property="name" column="sname"/><association property="teacher" javaType="com.kuang.pojo.Teacher" ><result property="name" column="tname"></result></association></resultMap></mapper>這里因為把teacher拼成了teahcer導致報錯,還有注意type的寫法是全類名。
select s.id sid,s.name sname,t.name tname:
取了三個別名
總結
以上是生活随笔為你收集整理的mybatis复杂查询环境 多对一的处理 按照结果嵌套处理和按照查询嵌套处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: redis设置密码和启动 redis数据
- 下一篇: promise的应用和在VUE中使用ax