mybatis一对多的配置

基本配置与onetoone的类似,不同的是一对多用到了两个新的标签
mybatis一对多的配置_第1张图片
下面是一个一对多的例子:


<select id="getClass3" parameterType="int" resultMap="ClassResultMap3">
select  *  from  class  c,  teacher  t,student  s  where  c.teacher_id=t.t_id  and  c.C_id=s.class_id  and
c.c_id=#{id}
select>
<resultMap type="_Classes" id="ClassResultMap3">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association property="teacher" column="teacher_id" javaType="_Teacher">
<id property="id" column="t_id"/>
<result property="name" column="t_name"/>
association>

<collection property="students" ofType="_Student">
<id property="id" column="s_id"/>
<result property="name" column="s_name"/>
collection>
resultMap>

<select id="getClass4" parameterType="int" resultMap="ClassResultMap4">
select * from class where c_id=#{id}
select>
<resultMap type="_Classes" id="ClassResultMap4">
<id property="id" column="c_id"/>
<result property="name" column="c_name"/>
<association  property="teacher"  column="teacher_id"  javaType="_Teacher"
select="getTeacher2">association>
<collection property="students" ofType="_Student" column="c_id" select="getStudent">collection>
resultMap>
<select id="getTeacher2" parameterType="int" resultType="_Teacher">
SELECT t_id id, t_name name FROM teacher WHERE t_id=#{id}
select>
<select id="getStudent" parameterType="int" resultType="_Student">
SELECT s_id id, s_name name FROM student WHERE class_id=#{id}
select>

sql映射文件一定要记得到conf.xml中注册,有设置别名的记得到到conf.xml里设置

你可能感兴趣的:(mybatis)