關(guān)于MyBatis 查詢數(shù)據(jù)時屬性中多對一的問題(多條數(shù)據(jù)對應(yīng)一條數(shù)據(jù))
數(shù)據(jù)表
CREATE TABLE `teacher`( id INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, PRIMARY KEY (id)) ENGINE=INNODB DEFAULT CHARSET=utf8;INSERT INTO `teacher`(id,`name`) VALUES(1,’大師’);CREATE TABLE `student`( id INT(10) NOT NULL, `name` VARCHAR(30) DEFAULT NULL, `tid` INT(10) DEFAULT NULL, PRIMARY KEY(id), KEY `fktid` (`tid`), CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)) ENGINE=INNODB DEFAULT CHARSET=utf8;INSERT INTO student(`id`,`name`,`tid`) VALUES(1,’小明’,1);INSERT INTO student(`id`,`name`,`tid`) VALUES(2,’小紅’,1);INSERT INTO student(`id`,`name`,`tid`) VALUES(3,’小張’,1);INSERT INTO student(`id`,`name`,`tid`) VALUES(4,’小李’,1);INSERT INTO student(`id`,`name`,`tid`) VALUES(5,’小王’,1);
Teacher 類
public class Teacher { private int id; private String name;}
Student 類
public class Student { private int id; private String name; private Teacher teacher;}
查詢接口
public interface StudentMapper { // 查詢嵌套處理 - 子查詢 List<Student> getStudentList(); // 結(jié)果嵌套處理 List<Student> getStudentResult();}查詢嵌套處理(子查詢)
思路:先查詢出所有學(xué)生的數(shù)據(jù),再根據(jù)學(xué)生中關(guān)聯(lián)老師的字段 tid 用一個子查詢?nèi)ゲ樵兝蠋煹臄?shù)據(jù)
association:處理對象
property:實體類中屬性字段
column:查詢結(jié)果中需要傳遞給子查詢的字段
javaType:指定實體類
select:子查詢SQL
<mapper namespace='com.pro.dao.StudentMapper'> <!-- 按照查詢嵌套處理 1. 先查詢所有學(xué)生信息 2. 根據(jù)查詢出來學(xué)生的tid, 接一個子查詢?nèi)ゲ槔蠋? --> <resultMap type='com.pro.pojo.Student'> <result property='id' column='id'/> <result property='name' column='name'/> <!--復(fù)雜屬性需要單獨處理, 對象: association, 集合: collection --> <association property='teacher' column='tid' javaType='com.pro.pojo.Teacher' select='getTeacher'/> </resultMap> <select resultMap='StudentTeacher'> select * from student </select> <select resultType='com.pro.pojo.Teacher'> select * from teacher where id = #{id} </select></mapper>結(jié)果嵌套處理
思路:先把所有的信息一次性查詢處理, 然后配置字段對應(yīng)的實體類, 使用 association 配置
association:處理對象
property:實體類中屬性字段
javaType:指定實體類
<mapper namespace='com.pro.dao.StudentMapper'> <!-- 按照結(jié)果嵌套處理 1. 一次查詢出所有學(xué)生和老師的數(shù)據(jù) 2. 根據(jù)查詢的結(jié)果配置 association 對應(yīng)的屬性和字段 --> <resultMap type='com.pro.pojo.Student'> <result column='sid' property='id'/> <result column='sname' property='name'/> <!-- 根據(jù)查詢出來的結(jié)果, 去配置字段對應(yīng)的實體類 --> <association property='teacher' javaType='com.pro.pojo.Teacher'> <result column='tname' property='name'/> </association> </resultMap> <select resultMap='StudentResult'> SELECT s.id sid, s.name sname, t.name tname FROM student s, teacher t WHERE s.tid = t.id </select></mapper>
到此這篇關(guān)于MyBatis 查詢數(shù)據(jù)時屬性中多對一的問題(多條數(shù)據(jù)對應(yīng)一條數(shù)據(jù))的文章就介紹到這了,更多相關(guān)MyBatis 查詢數(shù)據(jù)內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
