MyBatis Multi-pair mapping first knowledge tutorial _java

Source: Internet
Author: User

MyBatis is an excellent persistence layer framework that supports common SQL queries, stored procedures, and advanced mappings. MyBatis eliminates the manual setting of almost all JDBC code and parameters and the retrieval encapsulation of the result set. MyBatis can use simple XML or annotations for configuration and raw mappings, mapping interfaces and Java Pojo (Plain old Java Objects, normal Java objects) to records in the database.

In the last article to introduce you to mybatis one-to-one mapping of the first course.

Here is a mybatis of multiple mapping knowledge, the details are as follows:

Many examples are many, such as the relationship between curriculum and students, a course can have a number of students elective, and a student can also take a number of subjects. The relationship between teachers and students, a teacher has a number of students, a student has more than one teacher.
Take the relationship between students and the curriculum as an example.

There are two scenarios when we set up a data table:

First type:

When setting up a student datasheet, place the foreign key field of a course,

When creating a course datasheet, store a student's foreign key field.

But there is a big drawback, that is, if I want to delete the student table, there is a course table foreign key field,

Similarly, I want to delete the course table, but there is a student table foreign key field, ah, not easy to do.

The second type:

We set up student and course tables, and separate the fields and records in both tables,

Another common Student_course table, as an intermediate table, holds student and course foreign keys.

So it's convenient for us to delete the form, so we use this scheme.

Database Scripts

--Multi-many-to-many mapping--delete database drop db if exists mybatis;
--Creating database Create db if not exists mybatis default character set UTF8;
--Select database use MyBatis;
--Delete Datasheet drop table if exists student;
Drop table if exists course;
drop table if exists student_course;
--Creates a datasheet create TABLE student (SID Int (255), sname varchar (), Constraint Pk_sid primary key (SID));
CREATE TABLE course (CID int (255), CNAME varchar, constraint pk_cid key (CID)); CREATE TABLE student_course (SID Int (255), Cid Int (255), Constraint Pk_sid_cid primary key (SID,CID), constraint fk_sid for
Eign key (SID) references student (SID), constraint fk_cid foreign key (CID) References course (CID));
--test data insert into student (Sid,sname) VALUES (1, ' haha ');
INSERT into student (Sid,sname) VALUES (2, ' ha ');
Insert into course (Cid,cname) VALUES (1, ' Java '); Insert into course (Cid,cname) VALUES (2, '.
NET ');
Insert into Student_course (SID,CID) values (1,1);
Insert into Student_course (SID,CID) values (1,2); INSERT INTO StudeNt_course (SID,CID) values (2,1); Insert into Student_course (SID,CID) values (2,2);

New Many2many. Course.java class

Package many2many;
Import java.io.Serializable;
Import java.util.ArrayList;
Import java.util.List;
/** *
@author Administrator * *
/@SuppressWarnings ("Serial") Public
class Course Implements serializable{
private Integer CID;
Private String CNAME;
Private list<student> students = new arraylist<student> ();
Public Integer Getcid () {return
cid;
}
public void Setcid (Integer cid) {
this.cid = cid;
}
Public String Getcname () {return
cname;
}
public void Setcname (String cname) {
this.cname = CNAME;
}
Public list<student> getstudents () {return
students;
}
public void Setstudents (list<student> students) {
this.students = students;
}
}

New Many2many. Student.java class

Package many2many;
Import java.io.Serializable;
Import java.util.ArrayList;
Import java.util.List;
/** *
Student class
* @author Administrator
* * *
/@SuppressWarnings ("Serial") Public
class Student Implements Serializable {
private Integer sid;
Private String sname;
Private list<course> courses = new arraylist<course> ();
Public Integer GetSID () {return
sid;
}
public void Setsid (Integer sid) {
this.sid = sid;
}
Public String Getsname () {return
sname;
}
public void Setsname (String sname) {
this.sname = sname;
}
Public list<course> getcourses () {return
courses;
}
public void setcourses (list<course> courses) {
this.courses = courses;
}
}

New studentmapper.xml files and coursemapper.xml files

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < Mapper namespace= "Studentmapper" > <resultmap type= "Many2many".
Student "id=" Studentmap "> <id property=" Sid "Column=" Sid "/> <result" property= sname "column=" sname "/> </resultMap> </mapper> <?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < Mapper namespace= "Coursenamespace" > <resultmap type= "Many2many".
Course "id=" Coursemap "> <id property=" cid "column=" cid "/> <result property=" CNAME "column=" cname "/> </resultMap> <!--inquiry "haha" elective those courses--> <select id= "Findallbyname" parametertype= "string" resultmap= " Coursemap "> select C.cname,c.cid from student S,course C,student_course sc where s.sid = sc.sid and c.cid = Sc.cid and
S.sname = #{sname}; </select>
</mapper> 

New persistence Layer Class Studentcoursedao.java class

Package many2many;
Import Java.util.Iterator;
Import java.util.List;
Import One2many. Student;
Import org.apache.ibatis.session.SqlSession;
Import Org.junit.Test;
Import util. Mybatisutil;
public class Studentcoursedao {
/**
* query "haha" elective those courses
* @param name of the student name
* @return
* @throws Exception
*
/Public list<course> findallbyname (String name) throws exception{sqlsession
sqlsession = null;
try {
sqlsession = mybatisutil.getsqlsession ();
Return Sqlsession.selectlist ("Coursenamespace.findallbyname", name);
catch (Exception e) {
e.printstacktrace ();
throw e;
} finally{
mybatisutil.closesqlsession ();
}
@Test public
void Testfindallbyname () throws exception{
Studentcoursedao dao = new Studentcoursedao ();
list<course> courses = dao.findallbyname ("haha");
for (Course course:courses) {
System.out.println (course.getcid () + ":" +course.getcname ());}}}

To load a configuration file in a Mybatis.cfg.xml file

<!--load mapping file-->
<mappers>
<mapper resource= "One2one/cardmapper.xml"/>
<mapper Resource= "One2one/studentmapper.xml"/>
<mapper resource= "One2many/grademapper.xml"/>
< Mapper resource= "One2many/studentmapper.xml"/> <mapper resource= "Many2many/studentmapper.xml
"/>
<mapper resource= "Many2many/coursemapper.xml"/>
</mappers>

The above is a small set to introduce the MyBatis many maps to the first course, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.