注解方式整合Mybatis**

 (1)创建一个用于对数据库表t_comment数据操作的接口CommentMapper 

 

```java

      @Mapper

      public interface CommentMapper {

          @Select("SELECT * FROM t_comment WHERE id =#{id}")

          public Comment findById(Integer id);

      }

```

 

```

@Mapper注解表示该类是一个MyBatis接口文件,并保证能够被Spring Boot自动扫描到Spring容器中

 

对应的接口类上添加了@Mapper注解,如果编写的Mapper接口过多时,需要重复为每一个接口文件添加@Mapper注解

 

为了解决这种麻烦,可以直接在Spring Boot项目启动类上添加@MapperScan("xxx")注解,不需要再逐个添加

 

@Mapper注解,@MapperScan("xxx")注解的作用和@Mapper注解类似,但是它必须指定需要扫描的具体包名

```

 

(2)编写测试方法

 

```java

@RunWith(SpringRunner.class)

@SpringBootTest

class SpringbootPersistenceApplicationTests {

 

    @Autowired

    private CommentMapper commentMapper;

 

    @Test

    void contextLoads() {

        Comment comment = commentMapper.findById(1);

        System.out.println(comment);

    }

}

```

 

打印结果:

 

<img src="./images/image-20191227153811292.png" alt="image-20191227153811292" style="zoom:67%;" />

 

​         控制台中查询的Comment的aId属性值为null,没有映射成功。这是因为编写的实体类Comment中使用了驼峰命名方式将t_comment表中的a_id字段设计成了aId属性,所以无法正确映射查询结果。

 

为了解决上述由于驼峰命名方式造成的表字段值无法正确映射到类属性的情况,可以在Spring Boot全局配置文件application.properties中添加开启驼峰命名匹配映射配置,示例代码如下 

 

```properties

#开启驼峰命名匹配映射

mybatis.configuration.map-underscore-to-camel-case=true

```

 

打印结果:

 

​                             <img src="./images/image-20191227154947834.png" alt="image-20191227154947834" style="zoom:67%;" />

 

 

 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~·

学习让人快乐,学习更让人觉得无知!学了1个多月的《Java工程师高薪训练营》,才发现自己对每个技术点的认知都很肤浅,根本深不下去,立个Flag:每天坚持学习一小时,一周回答网上3个技术问题,把自己知道都分享出来。
posted @ 2020-06-05 17:53  西西宝贝  阅读(102)  评论(0)    收藏  举报