開發者學堂課程【MyBatis持久層架構入門:一對多的處理】學習筆記,與課程緊密聯系,讓使用者快速學習知識。
課程位址:
https://developer.aliyun.com/learning/course/21/detail/448一對多的處理
内容介紹:
1. association、property、JavaType、cloumn、select
2. 一對多的處理
3. Collection 元素
4. 編寫映射檔案 teacher.mapper.xml 的兩種方式
1、 association、property、JavaType、cloumn、select
association:關聯屬性;
property:屬性名;
JavaType:屬性的類型;
cloumn:關聯屬性在多的一方表中列名;
select:表示查詢;
2、 一對多的處理
1. 資料庫表的設計(不需要改變,與多對一一緻)
2. 實體類
Ø
Student.java
public class Student {
private int id;
private String name;
public int getId(){
return id;
{
public void setId(int id) {
this.id=.id;
}
public String getName(){
return name;
{
public void setName (String name) {
this.name= name;
}
}
Ø
Teather.java
public class Teacher{
private int id;
private String name;
private List students;
public int getId(){
return id;
}
public void setId(int id) {
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name)
this.name= name;
}
public List getStudents(){
return students;
}
public void setStudents (List students){
this.students = students;
}
}
3、 Collection元素
Collection 元素
(result property="subject"column="post_aubject"/>
collection 元素的作用差不多和 association 元素的作用一樣。
事實上,它們非常相似,以至于再對相似點進行描述會顯得備援,是以我們隻關注它們的不同點。
繼續我們上面的例子,一個Blog隻有一個Author。
但一個Blog有許多文章(文章)。
在Blog類中,會像下面這樣定義相應屬性:
集合嵌套選擇(Nested Select for Collection)
首先我們使用嵌套選擇來加載Blog的文章。
SELECT* FROM BLOG WHERE ID = #{id]
4、編寫映射檔案teacher.mapper.xml的兩種方式
第一種:
select s.id sid,s.name sname,s.tid stid,t.id tid,t.name tname from student s,teacher t where s.tid=t.id and t.id=#{id}
第二種:
select* from teacher where id=#{id}
column="id"
select="cn.sxt.entity.student.mapper.getStudentByTid"
Student mapper xml
select* from student where tid=#{id}