MyBatis执行流程

搭建一个简单的Mybatis+Maven项目

Maven依赖

  
        
            log4j
            log4j
            1.2.16
        
        
        
            org.mybatis
            mybatis
            3.2.6
        
        
        
            mysql
            mysql-connector-java
            5.1.12
        
        
        
            junit
            junit
            4.12
        
        
            org.projectlombok
            lombok
            1.14.8
        

代码


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

public interface StudentDao {
        public void insert(Student student);
        public Student findUserById (int id);
        public List findAllUsers();
}

public class StudentDaoTest {
    @Test
    public void findUserById() {
        SqlSession sqlSession = getSessionFactory().openSession();
        StudentDao userMapper = sqlSession.getMapper(StudentDao.class);
        Student user = userMapper.findUserById(1);
        System.out.println(user.toString());
    }

    //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }
}

配置文件

//configuration.xml




    
    
    
    
        
    
    
        
            
            
                
                
                
                
            
        
    

    
    
        
    

//userDao-mapping.xml



    
   

通过SqlSessionFactory获取SqlSession

执行流程

MyBatis执行流程_第1张图片

获取MapperProxy

执行流程

MyBatis执行流程_第2张图片

获取Excutor

执行流程

MyBatis执行流程_第3张图片

你可能感兴趣的:(MyBatis执行流程)