本文共 9374 字,大约阅读时间需要 31 分钟。
首先给大家推荐几个网页:
没事看看 - MyBatis工具:www.mybatis.tk
入门
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       集合,是说明学习这门课程的所有学生17     private List          student;18     public CoursesBean() {19         super();20     }21     public CoursesBean(Integer id, String name, List            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              getStudent() {40         return student;41     }42     public void setStudent(List                student) {43         this.student = student;44     }45     @Override46     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        courses;17     public StudentBean() {18         super();19         // TODO Auto-generated constructor stub20     }21     public StudentBean(Integer id, String name, List          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            getCourses() {40         return courses;41     }42     public void setCourses(List              courses) {43         this.courses = courses;44     }45     @Override46     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 id10      * @return11      */12     public CoursesBean findCouById(int id);13     14     /**15      * 要求查课时,将选课的学生一并查出16      * @param id17      * @return18      */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      * @return10      */11     public StudentBean findStuById(int id);12     13     /**14      * 要求查询学生时,将学生选择的课程查出15      * @param id16      * @return17      */18     public StudentBean findStuAndCou(int id);19 20 }   
4) 定义xml文件。CoursesMapper.xml StudentMapper.xml
mybatis实际是对XML进行操作,我们所有的方法都直接定义在XML中,写个接口只是为了更好的符合我们3层的思想.XML中只要有方法,就可以使用,而调用的方式就是:namespace+方法名;
CoursesMapper.xml

1 2 34 5 6 7 9 10 13 1411 12 15 22 23 24 25 28 29 30 31 33 36 37 4016 17 18 20 21 

StudentMapper.xml


1 2 34 5 6 9 107 8 11 15 18 19 22 25 2612 13 14 

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 [com.mysql.jdbc.JDBC4Connection@8f21d] 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: 110 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 Connection12 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 [com.mysql.jdbc.JDBC4Connection@16c65a9]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: 219 DEBUG 2016-02-27 09:56:54,152 org.apache.ibatis.logging.jdbc.BaseJdbcLogger: <== Total: 120 StudentBean [id=1, name=米兰, courses=[CoursesBean [id=1, name=语文, student=null], CoursesBean [id=2, name=数学, student=null]]]

转载地址:http://zchs.baihongyu.com/