MyBatis学习笔记(四) MyBatis关系映射

工程结构

MyBatis学习笔记(四) MyBatis关系映射_第1张图片

一对一关系实现

AddressMapper.xml





    
	
	
	
	
    
	
    

 

AddressMapper.java

public interface AddressMapper {
    public Address findById(Integer id);
}

StudentMapper.xml


    
    
    
    




StudentMapper.java新增方法findStudentWithAddress

public Student findStudentWithAddress(Integer id);

测试类

@Test
public void testFindStudentWithAddress() {
    logger.info("查询学生(带地址)");
    Student student=studentMapper.findStudentWithAddress(2);
    System.out.println(student);
}

一对多关系实现

一个年级中有很多学生、

GradeMapper.xml


    
    
    
    


GradeMapper.java

public interface GradeMapper {
    public Grade findById(Integer id);
}

StudentMapper.xml


    
    
    
    
    


StudentMapper.java新增方法findByGradeId

public Student findByGradeId(Integer gradeId);

Test

@Test
public void testFindGradeWithStudents() {
    logger.info("查询年级(带学生)");
    Grade grade=gradeMapper.findById(1);
    System.out.println(grade);
}

 

你可能感兴趣的:(Mybatis)