Mybatis加载 Mapper配置的四种方式

from https://mybatis.org/mybatis-3/zh/getting-started.html

方式一

使用注解sql查询

mybatis-config.xml

    
        
    

Main.java
  public void  way2() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            StudentMapper mapper = session.getMapper(StudentMapper.class);
            Student student = mapper.selectStudent(1);
            System.out.println(student.toString());
        }
    }
StudentMapper.java
public interface StudentMapper {
    @Select("SELECT * FROM student WHERE id = #{id}")
    Student selectStudent(Integer id);
}
方式二

优先级最高。类似方式一,唯一区别如下

mybatis-config.xml

    
         
    

方式三

使用xml 配置sql查询

StudentMapper.xml

    

StudentMapper.java
public interface StudentMapper {
    Student selectStudent(Integer id);
}
Main.java
 public void  way3() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        try (SqlSession session = sqlSessionFactory.openSession()) {
            Student student =session.selectOne("com.frank.mybatis.xml.StudentMapper.selectStudent", 1);
            System.out.println(student.toString());
        }
    }
方式四

类似方式三,唯一区别如下

mybatis-config.xml
 
      
  

你可能感兴趣的:(Mybatis加载 Mapper配置的四种方式)