Mybatis - collection配置表关联one-to-many

写在前言

  • one to one - association ;
    //单对一,使用association

  • one to many - collection ;
    //单对多,使用collection

  • Nested results - column is not necessary ,javaType is necessary !
    //使用嵌套结果,column 不是必需的,但是JavaType是必需的;

  • nested queries - column is necessary ,javaType is not necessary !
    //使用嵌套查询,column是必需的,JavaType不是必须的,子查询自定义resultType即可!!

表结构:

t_student 表拥有属性 class_id 对应 t_class表 t_id

Mybatis - collection配置表关联one-to-many_第1张图片

【1】更改Classes,添加属性

public class Classes {

	private int id;
	private String name;
	private Teacher teacher;
	private List list;
	...
}

【2】嵌套结果-获取Classes,Teacher and list

 
 
 	
 	
 	
 	
 	
 		
 		
 	
 	
 	
 	
 		
 		
 	
 

【3】嵌套查询–获取Classes,Teacher and list

	 
	
		 

	 
	 
	 
	 	
	 	

		
	 	
	 	
	 	
	 	
	 	
	 	
		
	 

【4】Test

获取SqlSessionFactory的工具类:

public static SqlSessionFactory getFactory(){
		/* flow the src dir*/
		String resource = "mybatis.xml";
		/*MybatisUtils.class.getResourceAsStream(resource)----- it's wrong !!!!
		 * please distinguish the two up and down 
		 * */
		InputStream inputStream = MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
		
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		
		
		return factory;
	}

测试方法

	@Test
	public void testSelect4(){
		/*set auto commit ,which equals to the above*/
		SqlSession session = MybatisUtils.getFactory().openSession(true);
		
		String statement = "com.web.mapper.classMapper.getClass4";
		/*return the effect rows*/
		Classes classes = session.selectOne(statement, 1);
		Teacher teacher = classes.getTeacher();
		List list = classes.getList();
		System.out.println("result.."+classes+','+classes.getClass());
		System.out.println(teacher);
		System.out.println(list);
	}

result as follows :

result..Classes [id=1, list=[Student [id=1, name=stu1], Student [id=2, name=stu2], Student [id=3, name=stu3]], name=计算机, teacher=Teacher [id=1, name=李明]],class com.web.model.Classes
Teacher [id=1, name=李明]
[Student [id=1, name=stu1], Student [id=2, name=stu2], Student [id=3, name=stu3]]

你可能感兴趣的:(#,MyBatis)