Mybatis入门(一)

1.MyBatis的开发流程

Mybatis的开发流程可以粗略的分为创建SqlSessionFactory、获取SqlSession以及执行SQL。SqlSessionFactory的创建比较固定,由SqlSessionFactoryBuilder创建,主要是指定一些数据源的信息,比较固定。创建完成SqlSessionFactory后,可以直接使用openSession()方法获取到SqlSession。SqlSession提供了许多方法,可以用来执行SQL语句。这里面比较灵活的是,使用SqlSession来执行SQL。

2.SqlSession执行SQL

 直接使用Mapper.xml文件

 Mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

Java代码

try (SqlSession session = sqlSessionFactory.openSession()) {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
}

这种方式直接通过 Mapper文件的namespace+sql语句id,直接就定位到具体的SQL语句,然后使用sqlSession执行。

 使用Mapper.xml文件结合Mapper接口

 Mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

Mapper接口

package org.mybatis.example;
public interface BlogMapper {
  Blog selectBlog(int id);
}

Java代码

try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
}

Mapper接口的全限定名要和Mapper.xml的namespace一致。这样才能根据接口信息找到对应的Mapper.xml,从而根据Mapper接口和Mapper.xml生成一个代理对象,可以通过这个代理对象的方法来执行mapper中的sql。这种方式更加灵活,尤其是和Spring整合后,自动扫描所有的Mapper接口和文件,生成Mapper接口的代理对象并注入Spring容器中,开发时可直接使用@Autowired注入。

 使用Mapper接口+注解

Mapper接口

package org.mybatis.example;
public interface BlogMapper {
  @Select("SELECT * FROM blog WHERE id = #{id}")
  Blog selectBlog(int id);
}

Java代码

try (SqlSession session = sqlSessionFactory.openSession()) {
  BlogMapper mapper = session.getMapper(BlogMapper.class);
  Blog blog = mapper.selectBlog(101);
}

当SQL语句比较简单的时候,也可以不写Mapper.xml文件,直接在接口中的方法上使用注解写SQL语句。

posted @ 2022-09-21 17:17  Lag_range  阅读(48)  评论(0)    收藏  举报