美文网首页
Mybatis加载 Mapper配置的四种方式

Mybatis加载 Mapper配置的四种方式

作者: ManrayHsu | 来源:发表于2021-01-12 19:31 被阅读0次

    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>
    

    相关文章

      网友评论

          本文标题:Mybatis加载 Mapper配置的四种方式

          本文链接:https://www.haomeiwen.com/subject/biueaktx.html