码迷,mamicode.com
首页 > 编程语言 > 详细

【spring boot+mybatis】注解使用方式(无xml配置)设置自动驼峰明明转换(),IDEA中xxDao报错could not autowire的解决方法

时间:2017-06-11 23:24:30      阅读:7911      评论:0      收藏:0      [点我收藏+]

标签:map   完全   htm   str   解决   自动   class   ide   http   

最近使用spring boot+mybatis,使用IntelliJ IDEA开发,记录一些问题的解决方法。

1、在使用@Mapper注解方式代替XXmapper.xml配置文件,使用@Select等注解配置sql语句的情况下,如何配置数据库字段名到JavaBean实体类属性命的自动驼峰命名转换?

使用spring boot后,越来越喜欢用注解方式进行配置,代替xml配置文件方式。mybatis中也可以完全使用注解,避免使用xml方式配置mapper。(参考  springboot(六):如何优雅的使用mybatis  http://www.ityouknow.com/springboot/2016/11/06/springboot(%E5%85%AD)-%E5%A6%82%E4%BD%95%E4%BC%98%E9%9B%85%E7%9A%84%E4%BD%BF%E7%94%A8mybatis.html

设置自动驼峰命名转换,在xml中可以直接配置mapUnderscoreToCamelCase属性。

 

但是使用注解方式时,经过一番查找资料才找到比较好的设置方法。如下:

在spring boot的配置文件application.properties中,加入配置项:

1 mybatis.configuration.mapUnderscoreToCamelCase=true
2 3 mybatis.configuration.map-underscore-to-camel-case=true

设为true表示开启驼峰转换。经过试验,两种配置方法都可以。但如果同时配置,前者mybatis.configuration.mapUnderscoreToCamelCase的优先级更高。

参考:

官方的配置说明 mybatis-spring-boot-autoconfigure – MyBatis Sring-BootStarter | Reference Documentation  http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration

SpringBoot之Mybatis - 王念博客  https://my.oschina.net/wangnian/blog/667764

另外查到有通过javaConfig方式,配置org.apache.ibatis.session.SqlSessionFactory的Bean,放入spring的对象池。mapUnderscoreToCamelCase是org.apache.ibatis.session.Configuration的一个属性,实例化Configuration对象并将其mapUnderscoreToCamelCase属性设为true,再使用这个Configuration对象作为SqlSessionFactory的配置即可使mapUnderscoreToCamelCase=true生效。

但是仅仅为了改变一个属性的值,就自己编码生成一个SqlSessionFactory未免太繁琐了些。使用在application.properties中配置的方法更方便。

 

2.mybatis管理的@Mapper的Dao,在使用@Autowire自动注入时,IDEA有红色报错“could not autowire”,但实际运行时正常,如何去除报错?

按照本人的理解,这个报错是由于Dao接口只添加了mybatis自定义的@Mapper注解,没有添加spring定义的@Component、@Repository等,所以IDEA不认为这是纳入Spring管理的Bean,导致在IDEA找不到autowire的Dao的来源。

查找解决方法,找到了这里的问答:

java - Idea inspects batis mapper bean wrong - Stack Overflow  https://stackoverflow.com/questions/25379348/idea-inspects-batis-mapper-bean-wrong

里面提到安装【MyBatis plugin】插件可以解决。我尝试安装之后,启动后在IDEA的Event窗口中有以下输出:

1 Mybatis Plugin: Mybatis Plugin is not activated yet. Click here to enter your license key to activate the plugin. You can also click here to purchase a license key to sponsor us making the plugin better. More features are on their way. Wish you happy coding with the plugin

看来是一个收费的插件,需要购买license,到官网看了下价格是¥39.99。

随后我又尝试安装了【Free MyBatis plugin】和【iBATIS/MyBatis mini-plugin】插件,但是都没有去除红色报错。

 

暂时记录到这里,后续解决后再更新。

【spring boot+mybatis】注解使用方式(无xml配置)设置自动驼峰明明转换(),IDEA中xxDao报错could not autowire的解决方法

标签:map   完全   htm   str   解决   自动   class   ide   http   

原文地址:http://www.cnblogs.com/zhangdong92/p/6986653.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!