MyBatis one-to-many bi-directional Association--mybatis Learning Notes VII

Source: Internet
Author: User

The association element is required to handle the has-one relationship, and the collection element is used to process the has many relationship. For example, if a teacher can guide multiple students at the same time, here's how to use the collection element to implement this mapping, with the task of querying the information of multiple students who are teachers and their guidance (this sample source code download page: http://down.51cto.com/ data/490947).

I. Adding related attributes for teacher entities

The following attributes are added to guide the student collection for the teacher entity:

Private List<student> supstudents; // Guiding students

and add setter and getter methods for it, skip over here.

Second, Teachermapper interface

To implement the teacher entity mapping, you should first create the Mapper interface as follows:

 Package Com.abc.mapper; Import Com.abc.domain.Teacher;  Public Interface Teachermapper {   public Teacher getById (int  ID);} 

Third, mapping files

The mapping file created for the teacher entity is as follows:

<?XML version= "1.0" encoding= "UTF8"?><!DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "><!--as before, the value of the namespace is the full name of the corresponding mapper interface -<Mappernamespace= "Com.abc.mapper.TeacherMapper"><!--The SQL statement that corresponds to the GetByID method in the Teachermapper interface. Query the information of the teacher and the students he/she directs. Because the teacher, the student all has the ID, the name, the gender and so on attribute, therefore to the teacher's field to have the alias -<SelectID= "GetById"ParameterType= "int"Resultmap= "Supervisorresultmap">Select T.id t_id, T.name t_name, T.gender t_gender,t.research_area T_research_area, T.title t_title,s.id,s.name, S.gender,s.major,s.gradefrom teacher T,student s where t.id=#{id}and s.supervisor_id = T.id</Select><!--Teacher Entity Mapping -<ResultmapID= "Supervisorresultmap"type= "Teacher"><ID Property= "id"column= "t_id"/><result Property= "Name"column= "T_name"/><result Property= "Gender"column= "T_gender"/><result Property= "Researcharea"column= "T_research_area"/><result Property= "title"column= "T_title"/><!--The collection element maps the properties of the Teacher's Guide student collection. Resultmap in the form of the ID of the namespace name. Resultmap, refer to Studentresultmap. Note that the field names/aliases for secondary students in the SELECT statement above should be consistent with the column attribute in Studentresultmap -<Collection Property= "Supstudents"Resultmap= "Com.abc.mapper.StudentMapper.studentResultMap"/></Resultmap></Mapper>

Accordingly, the mapping file for the student entity is as follows:

<?XML version= "1.0" encoding= "UTF8"?><!DOCTYPE Mapper Public "-//mybatis.org//dtd mapper 3.0//en" "Http://mybatis.org/dtd/mybatis-3-mapper.dtd "><Mappernamespace= "Com.abc.mapper.StudentMapper"><ResultmapID= "Studentresultmap"type= "Student"><ID Property= "id"column= "id"/><result Property= "Name"column= "Name"/><result Property= "Gender"column= "Gender"/><result Property= "Major"column= "Major"/><result Property= "Grade"column= "Grade"/><!--Accordingly, the SUPERVISORRESULTMAP is referenced here, and the name of the namespace is used. The form of the ID of the resultmap.  -<Association Property= "Supervisor"Resultmap= "Com.abc.mapper.TeacherMapper.supervisorResultMap"/></Resultmap></Mapper>

In the Src\resources directory of the project, create a new subdirectory mappers, which is used to store the mapping file uniformly. To enable MyBatis to find these mapping files, modify the Mappers element in its core configuration file Configuration.xml as follows:

 <!--  reference the mapping file as a relative path in classpath  -->  <  mappers  >  <  mapper  resource  = "Resources/mappers/studentmapper.xml"  />  <  mapper  resource  = "Resources/mappers/teachermapper.xml"  />  </ mappers  >  

Note: The resources directory is copied to the classes directory before the project is compiled (see Copy-resources and compile two target in the project generation file Build.xml), and the classes directory is added to the classpath by Ant.

Iv. implementation of the class

The execution class is Collectiondemo, and its contents are as follows:

Package Com.demo;import Org.springframework.context.applicationcontext;import Com.abc.mapper.studentmapper;import Com.abc.mapper.teachermapper;import Com.abc.domain.teacher;import Com.abc.domain.student;import Org.springframework.context.support.classpathxmlapplicationcontext;import Java.util.list;public Class Collectiondemo{private Static ApplicationContext ctx;static{//looking for resources/beans.xml file in classpath = new Classpathxmlapplicationcontext ("Resources/beans.xml");} public static void Main (string[] args) {//Request mapper from the spring container teachermapper mapper = (teachermapper) Ctx.getbean (" Teachermapper ");//query ID of 1 teacher teacher teacher = Mapper.getbyid (1); if (teacher = = null) {SYSTEM.OUT.PRINTLN (" The relevant teacher information was not found. ");} else{//Teacher Information System.out.println ("**********************************************"); System.out.println ("Teacher Name:" + "" + teacher.getname ()); System.out.println ("Teacher title:" + "" + Teacher.gettitle ()); System.out.println ("**********************************************"); System.out.println ("Directing Student Information:");//traverse-guided student for (Student S:teacher.getsupstudents ()) {System.out.println ("**********************************************"); System.out.println (S.getname () + "" + s.getgender () + "+ s.getgrade () +" "+ s.getmajor ());//access teacher from student SYSTEM.OUT.PR INTLN ("Instructor Research Direction:" + s.getsupervisor (). Getresearcharea ());} System.out.println ("**********************************************");}}}

As you can see, the object at the other end can be accessed from either end.

V. Modification of Build.xml

In order to run this program with Ant, you need to modify the run target in Build.xml to specify the class Collectiondemo as the execution class. As follows:

<Targetname= "Run"depends= "Compile"><!--specify Collectiondemo as the class to run -<JavaFork= "true"ClassName= "Com.demo.CollectionDemo"Classpathref= "Library"><!--Add the classes directory to the classpath of the project. ${targetdir} refers to the property element defined above Targetdir -<ClasspathPath= "${targetdir}"/></Java></Target>
The results of the operation are as follows:

MyBatis one-to-many bi-directional Association--mybatis Learning Notes VII

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.