最近在使用MyBatis3做項目。在使用注解實現Mapper的時候遇到了比較奇葩的問題:在實現數據的batch insert的時候總是報錯。好不容易可以正常插入了,但是又不能返回自增的主鍵id到實體bean中了。而這些問題在XML配置中都不存在。一方面可能是我能力有限,沒有找到合適的解決方案;另一方面可能與MyBatis自身對Java中注解的支持不夠給力有關系。
以下是MyBatis官網對Mapper Annotations的解釋:
Mapper Annotations
Since the very beginning, MyBatis has been an XML driven framework. The configuration is XML based, and the Mapped Statements are defined in XML. With MyBatis 3, there are new options available. MyBatis 3 builds on top of a comprehensive and powerful Java based Configuration API. This Configuration API is the foundation for the XML based MyBatis configuration, as well as the new Annotation based configuration. Annotations offer a simple way to implement simple mapped statements without introducing a lot of overhead.
NOTE : Java Annotations are unfortunately limited in their expressiveness and flexibility. Despite a lot of time spent in investigation, design and trials, the most powerful MyBatis mappings simply cannot be built with Annotations – without getting ridiculous that is. C# Attributes (for example) do not suffer from these limitations, and thus MyBatis.NET will enjoy a much richer alternative to XML. That said, the Java Annotation based configuration is not without its benefits.
翻譯:
(最初MyBatis是基於XML驅動的框架。MyBatis的配置是基於XML的,語句映射也是用XML定義的。對於MyBatis3,有了新的可選方案。MyBatis3 是建立在全面且強大的Java配置API之上的。 該配置API是MyBatis基於XML配置的基礎,也是基於注解配置的基礎。注解提供了簡單的方式去實現簡單的映射語句,不需要花費大量的開銷。
注意:很不幸的是,java注解在表現和靈活性上存在限制。雖然在調研、設計和測試上花費了很多時間,但是最強大的MyBatis映射功能卻無法用注解實現。這沒有什么可笑的。舉例來說,C#的特性就沒有這個限制,所以MyBatis.NET 能擁有一個功能豐富的多的XML替代方案。所以,Java基於注解的配置是依賴於其自身特性的。)
http://www.mybatis.org/mybatis-3/java-api.html
所以,我最終決定不使用注解來實現Mapper了,換成XML。雖然麻煩一點,但起碼會少一些奇葩問題出現。問題少也是提高效率的一個方面啊(傷心)。