Mybatis加载 Mapper配置的四种方式

2021-01-12  本文已影响0人  ManrayHsu

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

方式一

使用注解sql查询

mybatis-config.xml
<configuration>
    <mappers>
        <mapper class="com.frank.mybatis.xml.StudentMapper"/>
    </mappers>
</configuration>
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
<configuration>
    <mappers>
         <package name="com.frank.mybatis.xml"/>
    </mappers>
</configuration>
方式三

使用xml 配置sql查询

StudentMapper.xml
<mapper namespace="com.frank.mybatis.xml.StudentMapper">
    <select id="selectStudent" parameterType="java.lang.Integer" resultType="com.frank.mybatis.xml.Student">
        SELECT * FROM student WHERE id = #{id}
    </select>
</mapper>
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
 <mappers>
      <mapper url="file:///E:/develop/github/java/java-demo/frank-demo-ocr/src/main/resources/StudentMapper.xml"/>
  </mappers>
上一篇下一篇

猜你喜欢

热点阅读