Example of MyBatis multi-to-multiple storage -- MyBatis study note 17

Source: Internet
Author: User

Some netizens asked MyBatis many-to-many questions a few days ago. However, I am very fond of MyBatis. I have been busy for a long time and have no time to deal with this matter until now. Today, I will first write a multi-to-multiple-storage example, which is a preliminary response to this netizen. More related blog posts will be published in the future.

To demonstrate many-to-many scenarios, we can simulate students' course selection. One student can take multiple courses and one course can be selected by multiple students. Obviously, this is a many-to-many relationship. First create a curriculum as follows sample complete source code download: http://down.51cto.com/data/907686 ):

SET FOREIGN_KEY_CHECKS = 0; drop table if exists 'Course'; create table 'Course' ('id' int (11) not null AUTO_INCREMENT, 'course _ Code' varchar (20) not null comment 'course number', 'course _ name' varchar (50) not null comment 'course name', primary key ('id ')) ENGINE = InnoDB AUTO_INCREMENT = 2 default charset = utf8; -- returns Records of course -- -------------------------- insert into 'Course' VALUES ('1', 'zj01', 'Data struct ');

Create a student elective table to save the student's elective information, as shown below:

SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- Table structure for 'student _ course' -- ---------------------------- drop table if exists 'student _ course '; create table 'student _ course' ('id' int (11) not null AUTO_INCREMENT, 'student _ id' int (11) not null comment 'course selection student id ', 'Course _ id' int (11) not null comment 'id of the selected course', primary key ('id '), KEY 'student _ id' ('student _ id'), KEY 'course _ id' ('course _ id '), CONSTRAINT 'student _ course_ibfk_1 'foreign key ('student _ id') REFERENCES 'student' ('id'), CONSTRAINT 'student _ course_ibfk_2 'foreign key ('course _ id ') REFERENCES 'Course' ('id') ENGINE = InnoDB AUTO_INCREMENT = 8 default charset = utf8;

As can be seen from the above, the student_id field and course_id field in the table are used as the foreign key and are associated with the primary key of the sudent table and the course table respectively.

Create the corresponding course entity class.

Package com. abc. domain; import java. util. list; public class Course {private int id; private String courseCode; // Course No. private String courseName; // Course name private List <Student> students; // public int getId () {return this. id;} public void setId (int id) {this. id = id;} public String getCourseCode () {return this. courseCode;} public void setCourseCode (String courseCode) {this. courseCode = courseCode;} public String getCourseName () {return this. courseName;} public void setCourseName (String courseName) {this. courseName = courseName ;}}

Add the selected course attributes for the Student Entity class as follows:

Private List <Course> courses; // The selected courses // getter and setterpublic List <Course> getCourses () {return this. courses;} public void setCourses (List courses) {this. courses = courses ;}

Next, compile the interface and file and DAO class for the Course object, which is the same as before. For more information, see the following code.

CourseMapper. java

package com.abc.mapper;import com.abc.domain.Course;public interface CourseMapper {public Course getById(int id);}

CourseMapper. xml

<? Xml version = "1.0" encoding = "utf8"?> <! DOCTYPE mapper PUBLIC "-// mybatis.org//DTD Mapper 3.0 //" http://mybatis.org/dtd/mybatis-3-mapper.dtd "> <mapper namespace =" com. abc. mapper. CourseMapper "> <! -- Query a course by id --> <select id = "getById" parameterType = "int" resultMap = "courseResultMap"> select id, course_code, course_namefrom course where id =#{ id} </select> <! -- Course entity ing --> <resultMap id = "courseResultMap" type = "Course"> <id property = "id" column = "id"/> <result property = "courseCode" column = "course_code"/> <result property = "courseName" column = "course_name"/> </resultMap> </mapper>

CourseDao. java

Package com. abc. dao; import com. abc. mapper. courseMapper; import com. abc. domain. course; public class CourseDao {private CourseMapper courseMapper; // setter and getter methods of studentMapper public void setCourseMapper (CourseMapper courseMapper) {this. courseMapper = courseMapper;} public CourseMapper getCourseMapper () {return this. courseMapper;} public Course getById (int id) {return this. courseMapper. getById (id );}}

The configurations of CourseMapper and CourseDao in spring are as follows:

<Bean id = "courseMapper" parent = "parentMapper"> <property name = "mapperInterface" value = "com. abc. mapper. CourseMapper"/> </bean> <! -- Inject courseMapper into courseDao --> <bean id = "courseDao" class = "com. abc. dao. courseDao "> <property name =" courseMapper "ref =" courseMapper "/> </bean>

To save the student course selection information, add a method in the StudentMapper interface as follows:

 

In the stuing file StudentMapper. xml, add the following insert statement:

<! -- Here param1 and param2 use the default naming method for MyBatis multi-parameter transfer. For details, see the author's blog: http://legend2011.blog.51cto.com/3018495/1024869 --> <insert id = "saveElecCourse" useGeneratedKeys = "true" keyColumn = "GENERATED_KEY"> insert into student_course (student_id, course_id) values (# {param1.id }, # {param2.id}) </insert>

Add the following method to the StudentDao class:

// Save the Student Course information public void saveElecCourse (student, course) {this. studentMapper. saveElecCourse (Student, Course );}

Next is the running class ManyToManyDemo. java ). In this class, we asked Liu Xiao, a student with id 8, to take the course data structure with id 1 ). The Code is as follows:

Package com. demo; import org. springframework. context. applicationContext; import com. abc. domain. student; import com. abc. domain. teacher; import org. springframework. context. support. classPathXmlApplicationContext; import com. abc. dao. studentDao; import com. abc. dao. courseDao; import com. abc. domain. course; public class ManyToManyDemo {private static ApplicationContext ctx; static {// search for resources/beans in the class path. xml file ctx = new ClassPathXmlApplicationContext ("resources/beans. xml ");} public static void main (String [] args) {// request the Dao object StudentDao studentDao = (StudentDao) ctx from the Spring container. getBean ("studentDao"); CourseDao courseDao = (CourseDao) ctx. getBean ("courseDao"); Student student = studentDao. getById (8); Course course = courseDao. getById (1); studentDao. saveElecCourse (student, course );}}

After running, the electives table has inserted the course selection information of this student, as shown in.


650) this. width = 650; "title =" manytomany.png "src =" http://www.bkjia.com/uploads/allimg/131228/11243055O-0.png "/>

 

 

MyBatis Study Notes series I: download and install ant

Prepare for MyBatis Study Notes Series II: ant getting started

MyBatis learning notes: MyBatis getting started

MyBatis Study Notes Series II: Example of adding, deleting, and modifying MyBatis

MyBatis Study Notes Series 3: association examples of MyBatis

MyBatis Study Notes Series 4: two forms of MyBatis association

MyBatis Study Notes Series 5: examples of integration between MyBatis and Spring

MyBatis Study Notes Series 6: examples of integration between MyBatis and Spring

MyBatis study notes 7: MyBatis one-to-multiple bidirectional Association

MyBatis Study Notes: MyBatis MapperScannerConfigurer Configuration

MyBatis Study Notes: two forms of MyBatis collection

MyBatis Study Notes Series 10: Log4j example of MyBatis logs

MyBatis Study Notes: example of how to annotate MyBatis with multiple parameters

MyBatis learning notes: Example of the default naming method for MyBatis multi-parameter transfer

MyBatis Study Notes: Example of Map mode for MyBatis multi-parameter transfer

MyBatis Study Notes: N + 1 in MyBatis

MyBatis Study Notes: a hybrid transfer of multiple parameters in MyBatis

MyBatis learning notes: Example of Spring declarative Transaction Management

MyBatis Study Notes: Example of MyBatis multiple-to-multiple storage

This article is from the "Xiao fan's column" blog, please be sure to keep this source http://legend2011.blog.51cto.com/3018495/1270547

Related Article

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.