Mybatis学习笔记(四)之一对多映射、多对多映射

1.   一对多映射

       一个专业可以对应一个或者多个学生。这意味着专业和学生之间存在一对多的映射关系。我们可以使用<collection>元素将 一对多类型的结果映射到 一个对象集合上。

准备两张表,分别是专业和学生信息

            

step1:定义两个bean  Stu、clazz

public class Stu {
	private int id;
	private int clazzId;
	private String name;
	private String sex;
	private int age;
public class Clazz {
  private int	 id;
  private String name;
  List<Stu> stus=new ArrayList<Stu>();

step2:主配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
  <package name="com.pojo"/>
</typeAliases>
	 <environments default="development">
		 <environment id="development">
			 <transactionManager type="JDBC"/>
			 <dataSource type="POOLED">
				 <property name="driver" value="com.mysql.jdbc.Driver"/>
				 <property name="url" value="jdbc:mysql://localhost:3306/mybatis4?useSSL=true"/>
				 <property name="username" value="root"/>
				 <property name="password" value="mysql"/>
			 </dataSource>
		 </environment>
	
	 </environments>
	 <mappers>
	     <!-- 对像和数据表的关系 -->
	     <mapper resource="com/mapper/StudentsMapper.xml"/>
	 </mappers>
</configuration>

step3:定义接口

public interface StudentsMapper {
   public List<Clazz> getAllClazz();
   public List<Stu> getAllStuByCId(int id);   
}

step4:配置映射文件,“实现接口”

<?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.StudentsMapper">

<resultMap type="clazz" id="clazzMap">
 <id property="id" column="id"/>
 <result property="name" column="name"/>
 <collection property="stus" select="getAllStuByCId" column="id"></collection>
</resultMap>

<select id="getAllStuByCId" resultType="stu" parameterType="int">
 select * from stu where clazz_id=#{id}
 </select>
 <select id="getAllClazz" resultMap="clazzMap">
    select * from clazz
 </select>
   
</mapper>

step5:测试

public class TestClazz {
  @Test
  public void getAllClazz() {
	  InputStream inputStream=TestClazz.class.getResourceAsStream("/mybatis-config.xml");
	  SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
	  SqlSession sqlSession=sqlSessionFactory.openSession();
	  StudentsMapper sm=sqlSession.getMapper(StudentsMapper.class);
	  
	  List<Clazz> list=sm.getAllClazz();
	  for(Clazz clazz:list) {
		  System.out.println(clazz);
	  }
  }
}

结果输出:

 Clazz [id=1, name=计算机, stus=[]]
Clazz [id=2, name=软件工程, stus=[Stu [name=李四, sex=F, age=23], Stu [name=张飞, sex=M, age=24], Stu [name=李明宇, sex=F, age=23]]]
Clazz [id=3, name=电气工程, stus=[Stu [name=小明, sex=M, age=21]]]

注:toString()方法已重写

2.多对多映射

  一个老师可以对应多个学生同时一个学生可以对应多名老师。这意味着老师和学生之间存在多对多的映射关系。我们可以使用两个一对多类型的映射来实现多对多。

准备三张表,分别是老师信息teacher、学生信息stu、老师和学生对应信息stu_tea。

         

step1:定义两个bean  Stu、Teacher

public class Teacher {
	private int id;
	private String name;
	 private int age;
	 private String sex;
	 private String course;
	 List<Stu> stus=new ArrayList<Stu>();
public class Stu {
	private int id;
	private int clazzId;
	private String name;
	private String sex;
	private int age;
	private List<Teacher> teas=new ArrayList<Teacher>();

step2:主配置文件

和上面一对多相同,只是修改了配置文件的位置

  <mapper resource="com/mapper/TeachersMapper.xml"/>

step3:定义接口

public interface TeachersMapper {
   //根据老师查找对应的学生
   public List<Teacher> GetAllTeachers();
   public List<Stu> GetAllStudentsById(int id);
   
   //根据学生查找对应的老师
   public List<Stu> GetAllStudents();
   public List<Teacher> GetAllTeachersById(int id);
}

step4:配置映射文件,“实现接口”,  这里的SQL语句使用了多表查询。

<?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.TeachersMapper">


<resultMap type="teacher" id="teaMap">
  <id property="id" column="id"/>
  <result property="name" column="name" />
  <result property="age" column="age" />
  <result property="sex" column="sex" />
  <result property="course" column="course" />
  <collection property="stus" select="GetAllStudentsById"  column="id"></collection>
</resultMap>

<resultMap type="stu" id="stuMap">
  <id property="id" column="id"/>
  <result property="name" column="name" />
  <result property="age" column="age" />
  <result property="sex" column="sex" />
  <collection property="teas" select="GetAllTeachersById"  column="id"></collection>
</resultMap>

<!-- 根据老师查找对应的学生 -->
<select id="GetAllStudentsById" resultType="stu" parameterType="int">
  select s.*,st.* from stu s,stu_tea st where st.stu_id=s.id and st.tea_id=#{id} 
</select>
<select id="GetAllTeachers" resultMap="teaMap">
   select * from teacher
</select>

<!-- 根据学生查找对应的老师 -->
<select id="GetAllTeachersById" resultType="teacher" parameterType="int">
  select t.*,st.* from teacher t,stu_tea st where st.tea_id=t.id and st.stu_id=#{id} 
</select>
<select id="GetAllStudents" resultMap="stuMap">
  select * from stu
</select>
</mapper>

step5:测试

public class TestDemo {
   
  InputStream inputStream=TestDemo.class.getResourceAsStream("/mybatis-config.xml");
  SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
  SqlSession sqlSession=sqlSessionFactory.openSession();
  TeachersMapper sm=sqlSession.getMapper(TeachersMapper.class);
	  
	@Test
	public void GetAllTeachers() {
		
		 List<Teacher> teachers=sm.GetAllTeachers();
		  for(Teacher t:teachers) {
			  System.out.println(t.getId()+"\t"+t.getName()+"\t"+t.getAge()+"\t"+t.getSex());
			  if(t!=null)
			  {
				  for(Stu stu:t.getStus()) {
					  System.out.println(stu);
				  }
			  }
			  System.out.println("--------------------------------------------------------------");
		  }
	}
	
	@Test
    public void GetAllStudents() {
    	
    	 List<Stu> stus=sm.GetAllStudents();
		  for(Stu stu:stus) {
			  System.out.println(stu);
			  if(stu!=null)
			  {
				  for(Teacher tea:stu.getTeas()) {
					  System.out.println(tea);
				  }
			  }
			  System.out.println("--------------------------------------------------------------");
		  }
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值