1. 程式人生 > >MyBatis學習筆記(三) 關聯關係

MyBatis學習筆記(三) 關聯關係

 

首先給大家推薦幾個網頁:

http://blog.csdn.net/isea533/article/category/2092001 沒事看看 - MyBatis工具:www.mybatis.tk

http://www.mybatis.org/mybatis-3/zh/getting-started.html 入門

http://www.mybatis.tk/

http://mbg.cndocs.tk/

http://edu.51cto.com/course/course_id-1354.html  mybatis視訊教程

 

一、多對多關係。

一般我們在設定多對多關係的時候,都是建立第三張關係表。

例子:學生t_student與課程t_courses,一個學生可以對應學習多門課程,一門課程對應可以有多名學生學習。第三張關係表t_stu_cou。

1)關係整理好,接著建立資料庫表,新增資訊。

 1 create table t_student(
 2  id int primary key auto_increment,
 3  student_name varchar(20)
 4 );
 5 
 6 create table t_courses(
 7 id  int primary key auto_increment,
 8 courses_name varchar(20)
 9 );
10 
11 create table t_stu_cou(
12  id int primary key auto_increment,
13  fk_stu_id int,
14  fk_cou_id int 
15 );

 新增資料。

 

 1 insert into t_student values (null,'米蘭');
 2 insert into t_student values (null,'凌雪');
 3 insert into t_student values (null,'成成');
 4 insert into t_student values (null,'睿懿');
 5 insert into t_student values (null,'瑞瑞');
 6 
 7 insert into t_courses values (null,'語文');
 8 insert into t_courses values (null,'數學');
 9 insert into t_courses values (null,'計算機');
10 insert into t_courses values (null,'java程式設計');
11 insert into t_courses values (null,'html');
12 
13 insert into t_stu_cou values (null,1,1);
14 insert into t_stu_cou values (null,1,2);
15 insert into t_stu_cou values (null,2,3);
16 insert into t_stu_cou values (null,2,4);
17 insert into t_stu_cou values (null,3,1);
18 insert into t_stu_cou values (null,3,5);
19 insert into t_stu_cou values (null,4,4);
20 insert into t_stu_cou values (null,4,2);

 2)建立JavaBean。

 CoursesBean.java

 1 package com.cy.mybatis.beans;
 2 
 3 import java.io.Serializable;
 4 import java.util.List;
 5 /**
 6  * manyTOmany
 7  * @author acer
 8  *
 9  */
10 public class CoursesBean implements Serializable{
11 
12     
13     private static final long serialVersionUID = 1L;
14     private Integer id;
15     private String name;
16    // 使用 List<StudentBean>集合,是說明學習這門課程的所有學生
17     private List<StudentBean> student;
18     public CoursesBean() {
19         super();
20     }
21     public CoursesBean(Integer id, String name, List<StudentBean> student) {
22         super();
23         this.id = id;
24         this.name = name;
25         this.student = student;
26     }
27     public Integer getId() {
28         return id;
29     }
30     public void setId(Integer id) {
31         this.id = id;
32     }
33     public String getName() {
34         return name;
35     }
36     public void setName(String name) {
37         this.name = name;
38     }
39     public List<StudentBean> getStudent() {
40         return student;
41     }
42     public void setStudent(List<StudentBean> student) {
43         this.student = student;
44     }
45     @Override
46     public String toString() {
47         return "CoursesBean [id=" + id + ", name=" + name + ", student="
48                 + student + "]";
49     }
50     
51 
52 }

 StudentBean.java

 

 1 package com.cy.mybatis.beans;
 2 
 3 import java.io.Serializable;
 4 import java.util.List;
 5 /**
 6  * manyTOmany
 7  * @author acer
 8  *
 9  */
10 public class StudentBean implements Serializable{
11 
12     private static final long serialVersionUID = 1L;
13      
14     private Integer id;
15     private String name;    
16     private List<CoursesBean> courses;
17     public StudentBean() {
18         super();
19         // TODO Auto-generated constructor stub
20     }
21     public StudentBean(Integer id, String name, List<CoursesBean> courses) {
22         super();
23         this.id = id;
24         this.name = name;
25         this.courses = courses;
26     }
27     public Integer getId() {
28         return id;
29     }
30     public void setId(Integer id) {
31         this.id = id;
32     }
33     public String getName() {
34         return name;
35     }
36     public void setName(String name) {
37         this.name = name;
38     }
39     public List<CoursesBean> getCourses() {
40         return courses;
41     }
42     public void setCourses(List<CoursesBean> courses) {
43         this.courses = courses;
44     }
45     @Override
46     public String toString() {
47         return "StudentBean [id=" + id + ", name=" + name + ", courses="
48                 + courses + "]";
49     }
50     
51 
52 }

3) 定義介面  

CoursesMapper.java

 

 1 package com.cy.mybatis.mapper;
 2 
 3 import com.cy.mybatis.beans.CoursesBean;
 4 
 5 public interface CoursesMapper {
 6     
 7     /**
 8      * 根據id查詢課程
 9      * @param id
10      * @return
11      */
12     public CoursesBean findCouById(int id);
13     
14     /**
15      * 要求查課時,將選課的學生一併查出
16      * @param id
17      * @return
18      */
19     public CoursesBean findCouAndStu(int id);
20 
21 
22     
23 
24 }

StudentMapper.java

 

 1 package com.cy.mybatis.mapper;
 2 
 3 import com.cy.mybatis.beans.StudentBean;
 4 
 5 public interface StudentMapper {
 6     /**
 7      * 根據id值查詢學生資訊
 8      * @param id
 9      * @return
10      */
11     public StudentBean findStuById(int id);
12     
13     /**
14      * 要求查詢學生時,將學生選擇的課程查出
15      * @param id
16      * @return
17      */
18     public StudentBean findStuAndCou(int id);
19 
20 }

 

 4) 定義xml檔案。CoursesMapper.xml    StudentMapper.xml

 mybatis實際是對XML進行操作,我們所有的方法都直接定義在XML中,寫個介面只是為了更好的符合我們3層的思想.XML中只要有方法,就可以使用,而呼叫的方式就是:namespace+方法名;

 CoursesMapper.xml 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.cy.mybatis.mapper.CoursesMapper">
 4 
 5 
 6  <resultMap type="CoursesBean" id="coursesMap">
 7    <!--   在預設情況下,mybatis會自動在TypeAliasRegistry初始化的時候掛在很多jdk常用類,
 8                           所以javaType="java.lang.Integer"可以寫成javaType="Integer"-->  
 9                            
10     <id property="id" column="id" javaType="java.lang.Integer"/>
11     <result property="name" column="courses_name" javaType="java.lang.String"/>
12  </resultMap>
13 
14  <resultMap type="CoursesBean" id="couAndStu">
15     <id property="id" column="id" javaType="java.lang.Integer"/>
16     <result property="name" column="courses_name" javaType="java.lang.String"/>
17     
18     <!-- 對於一個屬性的型別是一個集合,就使用collection
19                       對於一個屬性的型別是一個類,就使用association   -->
20     <collection property="student" column="id" select="findStudentByCourses"></collection>
21  </resultMap>
22 
23 
24     
25  <select id="findCouById" resultMap="coursesMap">
26   select * from t_courses where id=#{id}
27  </select>
28  
29  
30  
31  <!-- 有學生表,課程表這兩張表都沒有外來鍵,我們就要使用第三張關聯表。我們就要根據課程表的fk_cou_id,把學生的id值得到。
32                對於多對多那麼這個學生的id值就不可能是一個值 。在資料庫裡就要使用in-->
33  <select id="findStudentByCourses" resultMap="com.cy.mybatis.mapper.StudentMapper.studentMap">
34     select * from t_student where id in (select fk_stu_id from t_stu_cou where fk_cou_id=#{id})
35  </select>
36     
37  <select id="findCouAndStu" resultMap="couAndStu">
38  select * from t_courses where id=#{id}
39  </select>
40 </mapper>

 

 StudentMapper.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.cy.mybatis.mapper.StudentMapper">
 4 
 5 <resultMap type="StudentBean" id="studentMap">
 6     <id property="id" column="id" javaType="java.lang.Integer"/>
 7     <result property="name" column="student_name" javaType="java.lang.String"/>
 8 </resultMap>
 9 
10 <resultMap type="StudentBean" id="studentAndCourses">
11      <id property="id" column="id" javaType="java.lang.Integer"/>
12      <result property="name" column="student_name" javaType="java.lang.String"/>
13      <collection property="courses" column="id" select="findCoursesByStudent"></collection>
14 </resultMap>
15     <select id="findStudentById" resultMap="studentMap">
16         select * from t_student where id = #{id}
17     </select>
18     
19     <select id="findStuAndCou" resultMap="studentAndCourses">
20         select * from t_student where id = #{id}
21     </select>
22     <select id="findCoursesByStudent" resultMap="com.cy.mybatis.mapper.CoursesMapper.coursesMap">
23         select * from t_courses where id in (select fk_cou_id from t_stu_cou where fk_stu_id = #{id})
24     </select>
25     
26 </mapper>

 5) 測試

 1 package com.cy.mybatis.service;
 2 
 3 import org.apache.ibatis.session.SqlSession;
 4 
 5 import com.cy.mybatis.beans.CoursesBean;
 6 import com.cy.mybatis.beans.StudentBean;
 7 import com.cy.mybatis.mapper.CoursesMapper;
 8 import com.cy.mybatis.mapper.StudentMapper;
 9 import com.cy.mybatis.tools.DBTools;
10 
11 
12 
13 public class ManyToManyService {
14     
15     public static void main(String[] args) {
16         
17         findStudentByCourses();
18         findCoursesByStudent();
19     }
20 
21     
22 
23     private static void findCoursesByStudent() {
24         SqlSession session = DBTools.getSession();
25         StudentMapper sm=session.getMapper(StudentMapper.class);
26         StudentBean sb=sm.findStuAndCou(1);
27         System.out.println(sb);
28         
29     }
30 
31 
32 
33     private static void findStudentByCourses() {
34         SqlSession session = DBTools.getSession();
35         CoursesMapper cm=session.getMapper(CoursesMapper.class);
36         CoursesBean cb=cm.findCouAndStu(2);
37         System.out.println(cb);
38     }
39 
40 }

 

 結果顯示:

 1 DEBUG 2016-02-27 09:56:53,852 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
 2 DEBUG 2016-02-27 09:56:54,070 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 586269.
 3 DEBUG 2016-02-27 09:56:54,070 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [[email protected]]
 4 DEBUG 2016-02-27 09:56:54,070 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: select * from t_courses where id=? 
 5 DEBUG 2016-02-27 09:56:54,105 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 2(Integer)
 6 DEBUG 2016-02-27 09:56:54,136 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ====>  Preparing: select * from t_student where id in (select fk_stu_id from t_stu_cou where fk_cou_id=?) 
 7 DEBUG 2016-02-27 09:56:54,136 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ====> Parameters: 2(Integer)
 8 DEBUG 2016-02-27 09:56:54,136 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <====      Total: 2
 9 DEBUG 2016-02-27 09:56:54,136 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 1
10 CoursesBean [id=2, name=數學, student=[StudentBean [id=1, name=米蘭, courses=null], StudentBean [id=4, name=睿懿, courses=null]]]
11 DEBUG 2016-02-27 09:56:54,136 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
12 DEBUG 2016-02-27 09:56:54,136 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 23881129.
13 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [[email protected]]
14 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: select * from t_student where id = ? 
15 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 1(Integer)
16 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ====>  Preparing: select * from t_courses where id in (select fk_cou_id from t_stu_cou where fk_stu_id = ?) 
17 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ====> Parameters: 1(Integer)
18 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <====      Total: 2
19 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 1
20 StudentBean [id=1, name=米蘭, courses=[CoursesBean [id=1, name=語文, student=null], CoursesBean [id=2, name=數學, student=null]]]

 

二 、繼承

最簡單的例子,寵物。

           資料庫

1 create TABLE t_pet(
2 id int  primary key auto_increment,
3 name varchar(20),
4 type varchar(20),
5 bone int,
6 fish int
7 );

 

 JavaBean

PetBean:

 

 1 package com.cy.mybatis.beans;
 2 
 3 import java.io.Serializable;
 4 
 5 public class PetBean implements Serializable {
 6 
 7     private static final long serialVersionUID = 8920733441991237426L;
 8 
 9     private Integer id;
10     private String name;
11     public PetBean() {
12         super();
13     }
14     public PetBean(Integer id, String name) {
15         super();
16         this.id = id;
17         this.name = name;
18         
19     }
20     public Integer getId() {
21         return id;
22     }
23     public void setId(Integer id) {
24         this.id = id;
25     }
26     public String getName() {
27         return name;
28     }
29     public void setName(String name) {
30         this.name = name;
31     }
32     
33     @Override
34     public String toString() {
35         return "PetBean [id=" + id + ", name=" + name + "]";
36     }
37     
38 }

CatBean:

 

 1 package com.cy.mybatis.beans;
 2 
 3 public class CatBean extends PetBean {
 4 
 5 
 6     private static final long serialVersionUID = 1978574561040340989L;
 7     
 8     private Integer fish;
 9     
10     public CatBean() {
11         super();
12         // TODO Auto-generated constructor stub
13     }
14     
15     public CatBean(Integer id, String name) {
16         super(id, name);
17         // TODO Auto-generated constructor stub
18     }
19 
20     public Integer getFish() {
21         return fish;
22     }
23     public void setFish(Integer fish) {
24         this.fish = fish;
25     }
26     
27     
28     @Override
29     public String toString() {
30         return "CatBean [fish=" + fish + ", toString()=" + super.toString()
31                 + "]";
32     }
33 }

DogBean:

 

 1 package com.cy.mybatis.beans;
 2 
 3 public class DogBean extends PetBean {
 4 
 5     private static final long serialVersionUID = -9020056420879737672L;
 6 
 7 
 8     private Integer bone;
 9 
10     public DogBean() {
11         super();
12     }
13     
14     
15     public DogBean(Integer id, String name) {
16         super(id, name);
17     }
18 
19 
20     public Integer getBone() {
21         return bone;
22     }
23 
24     public void setBone(Integer bone) {
25         this.bone = bone;
26     }
27 
28 
29     @Override
30     public String toString() {
31         return "DogBean [bone=" + bone + ", toString()=" + super.toString()
32                 + "]";
33     }
34 
35     
36     
37 }

   介面

PetMapper.java

 1 package com.cy.mybatis.mapper;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.annotations.Param;
 6 
 7 import com.cy.mybatis.beans.CatBean;
 8 import com.cy.mybatis.beans.DogBean;
 9 import com.cy.mybatis.beans.PetBean;
10 
11 public interface PetMapper {
12     /**
13      * 新增寵物貓
14      * @param cat
15      * @return
16      */
17     public int saveCat(@Param("c")CatBean cat);
18     
19     /**
20      * 新增寵物狗
21      * @param dog
22      * @return
23      */
24     public int saveDog(@Param("d")DogBean dog);
25     
26     /**
27      * 查詢所有的寵物
28      * @return
29      */
30     public List<PetBean> findAllPet();
31     
32     /**
33      * 查詢所有的寵物貓
34      * @return
35      */
36     public List<CatBean> findAllCat();
37     
38     
39 }

 XML

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.cy.mybatis.mapper.PetMapper">
 4     <resultMap id="petMap" type="PetBean">
 5         <id property="id" column="id" javaType="java.lang.Integer"/>
 6         <result property="name" column="name" javaType="java.lang.String"/>
 7         <!--discriminator:根據結果值決定使用哪個resultMap
 8             case:判斷條件  
 9                           它的表現很像 Java 語言中的 switch 語句。
10                           定義鑑別器指定了 column 和 javaType 屬性      
11             -->
12         <discriminator javaType="java.lang.String" column="type">
13             <case value="cat" resultType="CatBean">
14                 <result property="fish" column="fish" javaType="java.lang.Integer"/>
15             </case>
16             <case value="dog" resultType="DogBean">
17                 <result property="bone" column="bone" javaType="java.lang.Integer"/>
18             </case>
19         </discriminator>
20     </resultMap>
21     
22     <insert id="saveCat">
23         insert into t_pet(name,type,fish) values (#{c.name},'cat',#{c.fish})
24     </insert>
25     <insert id="saveDog">
26         insert into t_pet(name,type,bone) values (#{d.name},'dog',#{d.bone})
27     </insert>
28     
29     <select id="findAllPet" resultMap="petMap"> 
30         select * from t_pet
31     </select>
32     <select id="findAllCat" resultMap="petMap"> 
33         select * from t_pet where type = 'cat'
34     </select>
35 
36 </mapper>

測試:

 1 package com.cy.mybatis.service;
 2 
 3 import java.util.List;
 4 
 5 import org.apache.ibatis.session.SqlSession;
 6 
 7 import com.cy.mybatis.beans.CatBean;
 8 import com.cy.mybatis.beans.DogBean;
 9 import com.cy.mybatis.beans.PetBean;
10 import com.cy.mybatis.mapper.PetMapper;
11 import com.cy.mybatis.tools.DBTools;
12 
13 
14 
15 public class ExtendsService {
16     public static void main(String[] args) {
17 //        saveCat();
18 //        saveDog();
19         findAllCat();
20         findAllPet();
21     }
22 
23     private static void findAllCat() {
24         // TODO Auto-generated method stub
25         SqlSession session = DBTools.getSession();
26         PetMapper pm = session.getMapper(PetMapper.class);
27         List<CatBean> cats = pm.findAllCat();
28         for (CatBean catBean : cats) {
29             System.out.println(catBean);
30         }
31     }
32 
33     private static void findAllPet() {
34         // TODO Auto-generated method stub
35         SqlSession session = DBTools.getSession();
36         PetMapper pm = session.getMapper(PetMapper.class);
37         List<PetBean> pets = pm.findAllPet();
38         for (PetBean petBean : pets) {
39             System.out.println(petBean);
40         }
41     }
42 
43     private static void saveDog() {
44         // TODO Auto-generated method stub
45         SqlSession session = DBTools.getSession();
46         PetMapper pm = session.getMapper(PetMapper.class);
47         DogBean dog = new DogBean(null,"哈士奇");
48         dog.setBone(10);
49         pm.saveDog(dog);
50         session.commit();
51     }
52 
53     private static void saveCat() {
54         // TODO Auto-generated method stub
55         SqlSession session = DBTools.getSession();
56         PetMapper pm = session.getMapper(PetMapper.class);
57         CatBean cat = new CatBean(null,"大臉貓");
58         cat.setFish(10);        
59         pm.saveCat(cat);
60         session.commit();
61     }
62 }

 

結果顯示

 1 DEBUG 2016-02-27 11:51:56,857 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
 2 DEBUG 2016-02-27 11:51:57,073 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 8768896.
 3 DEBUG 2016-02-27 11:51:57,074 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [[email protected]]
 4 DEBUG 2016-02-27 11:51:57,076 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: select * from t_pet where type = 'cat' 
 5 DEBUG 2016-02-27 11:51:57,107 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 
 6 DEBUG 2016-02-27 11:51:57,121 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 1
 7 CatBean [fish=10, toString()=PetBean [id=1, name=大臉貓]]
 8 DEBUG 2016-02-27 11:51:57,122 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Opening JDBC Connection
 9 DEBUG 2016-02-27 11:51:57,133 org.apache.ibatis.datasource.pooled.PooledDataSource: Created connection 28157774.
10 DEBUG 2016-02-27 11:51:57,134 org.apache.ibatis.transaction.jdbc.JdbcTransaction: Setting autocommit to false on JDBC Connection [[email protected]]
11 DEBUG 2016-02-27 11:51:57,134 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==>  Preparing: select * from t_pet 
12 DEBUG 2016-02-27 11:51:57,134 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: ==> Parameters: 
13 DEBUG 2016-02-27 11:51:57,135 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <==      Total: 2
14 CatBean [fish=10, toString()=PetBean [id=1, name=大臉貓]]
15 DogBean [bone=10, toString()=PetBean [id=2, name=哈士奇]]

每件事都需要堅持!