首頁 > 軟體

MyBatis多對多關聯對映建立範例

2022-06-06 22:03:10

範例

【通過班級查詢老師資訊】

建立t_classes

建立t_classessTeacher

建立t_teacher

建立Classes

package com.po;
import java.util.List;
public class Classes {
	private Integer cid;
	private String cname;
	private List<Teacher> teachers;
	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<Teacher> getTeachers() {
		return teachers;
	}
	public void setTeachers(List<Teacher> teachers) {
		this.teachers = teachers;
	}
	@Override
	public String toString() {
		return "Classes [cid=" + cid + ", cname=" + cname + ", teachers=" + teachers + "]";
	}
}

建立Teacher

package com.po;
import java.util.List;
public class Teacher {
	private Integer tid;
	private String tname;
	private List<Classes> classes;
	public Integer getTid() {
		return tid;
	}
	public void setTid(Integer tid) {
		this.tid = tid;
	}
	public String getTname() {
		return tname;
	}
	public void setTname(String tname) {
		this.tname = tname;
	}
	public List<Classes> getClasses() {
		return classes;
	}
	public void setClasses(List<Classes> classes) {
		this.classes = classes;
	}
	@Override
	public String toString() {
		return "Teacher [tid=" + tid + ", tname=" + tname + "]";
	}
}

建立ClassesMapper.xml

<?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="com.mapper.ClassesMapper">
	<!-- 自定義結果對映 -->
	<resultMap type="com.po.Classes" id="ClassesWithTeacherResult">
		<id property="cid" column="cid"/>
		<result property="cname" column="cname"/>
		<!-- 多表關聯對映 -->
		<collection property="teachers" ofType="com.po.Teacher">
			<id property="tid" column="tid"/>
			<result property="tname" column="tname"/>
		</collection>
	</resultMap>
	<select id="findClassesWithTeacher" parameterType="Integer" resultMap="ClassesWithTeacherResult">
		select * from t_classes c,t_teacher t,t_classessTeacher ct
		where ct.cid=c.cid
		and ct.tid=t.tid
		and c.cid=#{cid}
	</select>
</mapper>

設定mybatis-config.xml

<!-- 設定Mapper的位置 -->
	<mappers>
		<mapper resource="com/mapper/ClassesMapper.xml"/>			
	</mappers>

建立ClassesDao

package com.dao;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.factory.SessionFactory;
import com.po.Classes;
public class ClassesDao {
	private SqlSession session=SessionFactory.getSqlSession();
	@Test
	public void findClassesWithTeacher() {
		Classes classess=session.selectOne("com.mapper.ClassesMapper.findClassesWithTeacher", 1);
		System.out.println(classess);
	}
}

執行 findClassesWithTeacher()方法

以上就是MyBatis多對多關聯對映建立範例的詳細內容,更多關於MyBatis多對多關聯對映的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com