MyBatis:一对多(狂神)

MyBatis:一对多(狂神)_第1张图片

MyBatis:一对多(狂神)_第2张图片 

MyBatis:一对多(狂神)_第3张图片 

MyBatis:一对多(狂神)_第4张图片 

MyBatis:一对多(狂神)_第5张图片 

 

db.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=&useUnicode=true&characterEncoding=utf-8
username=root
password=123456

 mybatis-config.xml:







    
        
        
        
    



    
        
        
        

    


    

    
        
        
    

    
        
            
            
            
                
                
                
                
            
        
    


    
        
        
    



Student:

package com.kuang.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    private int tid;
}

Teacher:

package com.kuang.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Teacher {
    private int id;
    private String name;

    //一个老师拥有多个学生
    private List students;
}

TeacherMapper:

package com.kuang.dao;

import com.kuang.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface TeacherMapper {


    //获取指定老师下所有的学生及老师的信息
    Teacher getTeacher(@Param("tid") int id);

    Teacher getTeacher2(@Param("tid") int id);
}

TeacherMapper.xml:




    


    
    
        
        
        
        
            
            
            
        
    



    
    
        
        
        
    

    

MyTest:

import com.kuang.dao.TeacherMapper;
import com.kuang.pojo.Teacher;
import com.kuang.utils.MybaitsUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class MyTest {
    //按结果集查询
    @Test
    public void test1(){
        SqlSession sqlSession= MybaitsUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
    //按嵌套查询
    @Test
    public void test2(){
        SqlSession sqlSession= MybaitsUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher2(1);
        System.out.println(teacher);
        sqlSession.close();
    }
}

test1:

MyBatis:一对多(狂神)_第6张图片

MyBatis:一对多(狂神)_第7张图片 

test2:

MyBatis:一对多(狂神)_第8张图片 

 

你可能感兴趣的:(MyBatis框架学习,java,MyBatis,mysql)