**注解方式整合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 CommentMappercommentMapper;

    @Test

    void contextLoads() {

        Comment comment = commentMapper.findById(1);

System.out.println(comment);

    }

}

```

打印结果:

<imgsrc="./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

```

打印结果:

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

 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这些内容,是从拉勾教育的《Java工程师高薪训练营》里学到的,课程内容非常全面,还有拉勾的内推大厂服务,推荐你也看看。

猜你喜欢

转载自www.cnblogs.com/lagoujiaoyu/p/13181470.html