MyBatis 第二十八章 MyBatis 的 DAO 层实现


MyBatis —— 第二十八章 MyBatis 的 DAO 层实现


1. 传统开发方式

1.1. 编写 UserMapp 接口

/**
 * @author gregPerlinLi
 * @since 2021-10-08
 */
public interface UserMapper (
    /**
     * FInd all
     *
     * @return User list
     * @throws IOException exception
     */
    List<User> findAll() throws IOException;
)

1.2. 编写 UserMapperImperl 实现

/**
 * @author gregPerlinLi
 * @since 2021-10-08
 */
public class UserMapperImpl implements UserMapper &#123;
    @Override
    public List<User> findAll() throws IOException &#123;
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession.selectList("userMapper.findAll");
    &#125;
&#125;

1.3. 编写 Service 层

/**
 * @author gregPerlinLi
 * @since 2021-10-08
 */
public class ServiceDemo &#123;
    public static void main(String[] args) throws IOException &#123;
        // Create Dao layer object, the current Dao layer implementation is manual creation
        UserMapper userMapper = new UserMapperImpl();
        List<User> all = userMapper.findAll();
        System.out.println(all);
    &#125;
&#125;

2. 代理开发方式

2.1. 代理开发方式介绍

采用 MyBatis 的代理开发方式实现 DAO 层的开发,这种方式是我们后面进入企业的主流。

Mapper 接口开发方法只需要程序员编写 Mapper 接口(相当于 DAO 接口),由 MyBatis 框架根据接口定义创建接口的动态代理对象,代理对象的方法同上边 DAO 接口实现类方法。

Mapper 接口开发需要遵循以下规范:

  1. mapper.xml 文件中的 namespace 与 Mapper 接口的全限定名相同
  2. Mapper 接口方法名和 mapper.xml中定义的每个 SQL 的 id 相同
  3. Mapper 接口方法的输入参数类型和 mapper.xml 中定义的每个 SQL 的 parameterType 的类型相同
  4. Mapper 接口方法的输出参数类型和 mapper.xml 中定义的每个 SQL 的 resultType 的类型相同

2.2. 编写 UserMapper 接口

<mapper namespace="com.yourname.mapper.UserMapper">
    <select id="findById" parameterType="int" resultType="user">
        select * from user where id = #&#123;id&#125;
    </select>
</mapper>
public interface UserMapper &#123;
    User findById(int id);
&#125;

2.3. 测试代理方式

@Test
public void testProxyDao() throws IOException &#123;
    InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    // Gets the implementation class of the UserMapper interface generated by the mybatis framework
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    User user = userMapper.findById(1);
    System.out.println(user);
    sqlSession.close();
&#125;

3. 知识要点

MyBatis 的 DAO 层实现的两种方式:

  • 手动对 DAO 进行实现: 传统开发方式

  • 代理方式对 DAO 进行实现:

    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    


文章作者: gregPerlinLi
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 gregPerlinLi !
  目录