处理has-one关系需要用到association元素,而处理has many关系则需要用到collection元素。例如本例中,假设一 名教师可同时指导多名学生,下面就来介绍如何使用collection元素来实现这种映射,具体的任务是查询出教师及其指导的多个学生的信息(本示例源代 码下载页面:http://down.51cto.com/data/490947)。

一、为Teacher实体增加相关属性

为教师实体增加指导学生集合的属性如下:

private List<Student> supStudents;//指导学生

并为其增加setter和getter方法,这里略过。

二、TeacherMapper接口

为实现教师实体映射,应先创建映射器接口如下:

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

三、映射文件

为教师实体创建的映射文件如下:

<?xml version="1.0" encoding="utf8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--与以前一样,namespace的值是对应的映射器接口的完整名称-->
<mapper namespace="com.abc.mapper.TeacherMapper">
<!--TeacherMapper接口中getById方法对应的SQL语句。
查询教师及其指导的学生的信息。由于教师、学生都有
id、name、gender等属性,因此给教师的字段都起了别名-->
<select id="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.grade
from teacher t,student s where t.id=#{id}
and s.supervisor_id = t.id
</select>
<!--教师实体映射-->
<resultMap id="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"/>
<!--collection元素映射教师的指导学生集合的属性。resultMap
以命名空间名.resultMap的id的形式,引用studentResultMap。
需要注意的是,上面的select语句中学生的字段名/别名应与
studentResultMap中的column属性一致-->
<collection property="supStudents"
resultMap="com.abc.mapper.StudentMapper.studentResultMap"/>
</resultMap>
</mapper>

相应地,学生实体的映射文件如下:

<?xml version="1.0" encoding="utf8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.abc.mapper.StudentMapper">
<resultMap id="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"/>
<!--相应地,在此引用supervisorResultMap,亦采用
命名空间名.resultMap的id的形式。-->
<association property="supervisor"
resultMap="com.abc.mapper.TeacherMapper.supervisorResultMap"/>
</resultMap>
</mapper>

在工程的src\resources目录下新建子目录mappers,用来统一存放映射文件。为了能让MyBatis找到这些映射文件,修改其核心配置文件configuration.xml中的mappers元素如下:

<!--在classpath中以相对路径的形式引用映射文件-->
<mappers>
<mapper resource="resources/mappers/StudentMapper.xml"/>
<mapper resource="resources/mappers/TeacherMapper.xml"/>
</mappers>

注意:resources目录在工程编译前会被复制到classes目录下(详见工程生成文件build.xml中的copy-resources和compile这两个target),而classes目录会被ant添加到classpath中。

四、执行类

执行类为CollectionDemo,其内容如下:

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
{
//在类路径下寻找resources/beans.xml文件
ctx = new ClassPathXmlApplicationContext("resources/beans.xml");
}
public static void main(String[] args)
{
//从Spring容器中请求映射器
TeacherMapper mapper =
(TeacherMapper)ctx.getBean("teacherMapper");
//查询id为1的教师
Teacher teacher = mapper.getById(1);
if(teacher == null)
{
System.out.println("未找到相关教师信息。");
}
else
{
//教师信息
System.out.println("**********************************************");
System.out.println("教师姓名:" + " " + teacher.getName());
System.out.println("教师职称:" + " " + teacher.getTitle());
System.out.println("**********************************************");
System.out.println("指导学生信息:");
//遍历指导的学生
for(Student s : teacher.getSupStudents())
{
System.out.println("**********************************************");
System.out.println( s.getName() + " " + s.getGender() + " " + s.getGrade()
+ " " + s.getMajor());
//从学生端访问教师
System.out.println("指导教师研究方向:" + s.getSupervisor().getResearchArea());
}
System.out.println("**********************************************");
}
}
}

从中可看出,可以从任意一端访问另一端的对象。

五、修改build.xml

为了能用ant运行此程序,需修改build.xml中的run target,指定类CollectionDemo为执行类。如下:

<target name="run" depends="compile">
<!--指定CollectionDemo为要运行的类-->
<java fork="true" classname="com.demo.CollectionDemo"
classpathref="library">
<!--把classes目录添加到工程的classpath中。
${targetdir}是指引用上面定义的property元素targetdir-->
<classpath path="${targetdir}"/>
</java>
</target>
  运行结果如下:

MyBatis一对多双向关联——MyBatis学习笔记之七的更多相关文章

  1. JPA学习---第九节:JPA中的一对多双向关联与级联操作

    一.一对多双向关联与级联操作 1.创建项目,配置文件代码如下: <?xml version="1.0" encoding="UTF-8"?> < ...

  2. JPA中的一对多双向关联与级联操作

    学习Spring有两周时间了 , 个人觉得服务端主要实现的是数据关系的维护和数据结构的制定 , 以及由业务需求产生的CRUD , 只要保证对前端提供的接口稳定高效响应 , 具体的前端实现完全不关心. ...

  3. Hibernate从入门到精通(九)一对多双向关联映射

    上次的博文Hibernate从入门到精通(八)一对多单向关联映射中,我们讲解了一下一对多单向映射的相关内容,这次我们讲解一下一对多双向映射的相关内容. 一对多双向关联映射 一对多双向关联映射,即在一的 ...

  4. Hibernate(九)一对多双向关联映射

    上次的博文Hibernate从入门到精通(八)一对多单向关联映射中,我们讲解了一下一对多单向映射的相关 内容,这次我们讲解一下一对多双向映射的相关内容. 一对多双向关联映射 一对多双向关联映 射,即在 ...

  5. Hibernate 一对多双向关联Demo

    以Classes[班级]和Student[学生]为例的Demo //Classes.java public class Classes implements Serializable { privat ...

  6. hibernate 一对多双向关联 详解

    一.解析: 1.  一对多双向关联也就是说,在加载班级时,能够知道这个班级所有的学生. 同时,在加载学生时,也能够知道这个学生所在的班级. 2.我们知道,一对多关联映射和多对一关联映射是一样的,都是在 ...

  7. Hibernate中用注解配置一对多双向关联和多对一单向关联

    Hibernate中用注解配置一对多双向关联和多对一单向关联 Hibernate提供了Hibernate Annotations扩展包,使用注解完成映射.在Hibernate3.3之前,需单独下载注解 ...

  8. 【Visual C++】游戏编程学习笔记之七:键盘输入消息

     本系列文章由@二货梦想家张程 所写,转载请注明出处. 作者:ZeeCoder  微博链接:http://weibo.com/zc463717263 我的邮箱:michealfloyd@126.c ...

  9. Mybatis中使用association及collection进行一对多双向关联示例(含XML版与注解版)

    XML版本: 实体类: package com.sunwii.mybatis.bean; import java.util.ArrayList; import java.util.List; impo ...

随机推荐

  1. D&F学数据结构系列——红黑树

    红黑树 定义:一棵二叉查找树如果满足下面的红黑性质,则为一棵红黑树: 1)每个结点不是红的就是黑的 2)根结点是黑的 3)每个叶结点是黑的 4)如果一个结点是红的,它的两个儿子都是黑的(即不可能有两个 ...

  2. .net web部署(IIS Express && Nancy Self-Hosting)

    http://d.hatena.ne.jp/fkmt5/20140330/1396195246 [1]Nancy Web配置注意事项 添加url:netsh http add urlacl url=h ...

  3. Oracle的学习三:java连接Oracle、事务、内置函数、日期函数、转换函数、系统函数

    1.java程序操作Oracle java连接Oracle JDBC_ODBC桥连接 1.加载驱动: Class.forName("sun.jdbc.odbc.JdbcodbcDriver& ...

  4. Oracle的学习一:安装与卸载、sql *plus常用命令、Oracle用户管理

    1.为什么学习oracle? 性能优越: 小型数据库 中型数据库 大型数据库 acess.foxbase mysql.sql server.informix sybase.oracle.db2 复杂量 ...

  5. http://www.oschina.net/translate/elasticsearch-getting-started?cmp

    http://www.oschina.net/translate/elasticsearch-getting-started?cmp

  6. *[topcoder]TaroFriends

    http://community.topcoder.com/stat?c=problem_statement&pm=13005 好题.最暴力是试验2^n种跳法.然后有从结果入手,那么最终的左右 ...

  7. spring autoWire注解和@resource注解区别

    1.autoWire注解主要是按类型匹配.因为autowire的扫描机制,是按照接口类型来扫描bean的. 而JSR250 @resource注解是通过名称扫描注入的. @autowire注解的扫描方 ...

  8. ubuntu 下搭建vsftp

    1. 安装:sudo apt-get install vsftpd 2. 我的目的是建立个ftp,专门的账户访问,账户不可以登陆.不允许匿名登陆 3. 更改配置文件/etc/vsftpd.conf l ...

  9. C++工具系列博文合集

    http://www.cnblogs.com/itech/category/240779.html

  10. Lambda 表达式型的排序法

    int[] arry = {3,9,5,7,64,51,35,94 }; foreach (int i in arry.OrderBy(i => i)) Console.WriteLine(i) ...