接着上一篇Mybatis基于xml配置

这一篇讨论的是关于注解配置

一、创建接口StudenetMapper.java
mybatis基于注解配置二、写测试类
方法一:我们不用再写studentMapper.xml(可以看到接口studentMapper通过注解写的sql语句和在studentMapper.xml中写的增删改查sql语句是一样的),所以也不用在mybatis-configuration.xml对其进行注册;但是我们在测试代码里要添加一行代码session.getConfiguration().addMapper(StudentMapper.class);进行注册;接口StudentMapper是否需要注册呢?也不需要,否则它就会报如下错误:
mybatis基于注解配置方法二(不用写session.getConfiguration().addMapper(StudentMapper.class)):我们可以空写studentMapper.xml,然后在mybatis-configuration.xml进行注册也是可以运行的;值得注意的是此时namespace的值不再是studentMapper,而是Mapper.StudentMapper,对应的是StudentMapper这个接口
mybatis基于注解配置——————————————————————————————————————————————————————————
不过其实mapper更常用的方式是:

在mybatis中,映射文件中的namespace是用于绑定Dao接口的,即面向接口编程。

当你的namespace绑定接口后,你可以不用写接口实现类,mybatis会通过该绑定自动帮你找到对应要执行的SQL语句,如下:

假设定义了IArticeDAO接口

public interface IArticleDAO
{
   List<Article> selectAllArticle();
}

对于映射文件如下:

<mapper namespace="IArticleDAO">
    <select id="selectAllArticle" resultType="article">
            SELECT t.* FROM T_article t WHERE t.flag = '1' ORDER BY t.createtime DESC
     </select>

请注意接口中的方法与映射文件中的SQL语句的ID一一对应
则在代码中可以直接使用IArticeDAO面向接口编程而不需要再编写实现类

关于namespace另一用法,摘自Mapper中namespace的用法

相关文章:

  • 2021-09-08
  • 2020-11-06
  • 2018-08-15
  • 2018-10-31
  • 2021-02-18
  • 2018-07-23
  • 2019-02-19
  • 2021-09-07
猜你喜欢
  • 2020-04-26
  • 2018-10-11
  • 2018-07-11
  • 2018-09-19
  • 2019-09-02
  • 2018-05-23
  • 2018-06-25
  • 2021-03-27
相关资源
相似解决方案