dubbox在異構系統中的使用-整合mybatis全註解方式到spring
原來在spring中使用mybatis一直採用了mapper-xml配置檔案方式,編寫Mapper介面檔案,然後編寫對應的sql指令碼xml配置檔案,最後在spring-context.xml配置檔案中配置mapper。得益於eclipse良好的程式碼提示功能,整合並不困難。但在專案功能逐漸豐富的過程中,mapper-xml配置檔案越來越複雜,維護起來力不從心,很容易出現紕漏。
這次打算讓新的專案更易於維護,選定了mybatis的SQL指令碼註解功能,也遇到了不少小坑。列舉如下FYI:
1. 無法使用@Select、@Insert等註解,只有@SelectProvider註解。
解決方法:mybatis版本太低(原來使用了mybatis 3.3.0,跟spring-3.2.9 及 mybatis-spring 1.2.2 適配),修改為mybatis-3.4.5(適配spring-3.2.9的最高版本)。
2. 出現java.lang.AbstractMethodError: org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout() 錯誤。
解決方法:mybatis-spring版本低導致(原來採用了spring-3.2.9的依賴版本mybatis-spring-1.2.2),修改為mybatis-spring-1.3.0後該錯誤消失。
3. mybatis註解@Select如何採用動態SQL指令碼。
解決方法:mybatis-mapper-xml配置檔案對動態SQL指令碼解決的近乎完美,通過where、when、foreach等標籤,很容易編寫功能強大的動態SQL指令碼。@SelectProvider註解為了解決這個問題,支援程式設計實現動態SQL指令碼,但這種方式的程式碼量大、難以維護。考慮mybatis高版本既然提供了@Select註解,一定應該有動態SQL指令碼的功能。通過閱讀嘗試,把指令碼放到<script>標籤中即可實現動態SQL。於是可以看到:
@Select("<script>......</script>")
4. mybatis註解@Select文字過長怎麼辦?
解決辦法:哈哈這個問題我對結果很滿意~ 儘管支援註解,又支援冬天SQL,但是指令碼實在太長了~太長了~按閱讀習慣100個字元1行寫不下、2行也寫不下...
不過這個工程我用了純kotlin語言來編寫,不包括一行Java程式碼,於是kotlin有了多行字串的完美格式-開頭為"""(三個雙引號表示多行文字開始、不轉義),結尾也是"""(表示多行文字結束,不轉義)於是類似下面:
@Select("""<script> SELECT user_id AS `id`, user_name AS `name`, user_mobile AS mobile, user_email AS email , pass_hash AS passHash, user_status AS status, firm_id AS firmId , email_valid AS isEmailValid, email_token AS emailToken, user_token AS userToken FROM bw_user WHERE firm_id LIKE #{firmId} <when test='nameStr != null'> AND user_name LIKE #{nameStr} </when> </script>""") fun listUser(@Param("firmId") firmId: String, @Param("nameStr") nameStr: String): List<BwUser>
腫麼樣~開森吧:D
5. mybatis配置檔案mybatis-config.xml(這個檔案貌似多餘,不過我不去驗證了,算這篇文章的小彩蛋吧:-;)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties" />
<typeAliases>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper class="com.abel.bigmeter.mapper.UserMapper"></mapper>-->
</mappers>
</configuration>
6. spring-context-xml配置檔案spring/application-config.xml,常規配置除了採用了阿里的dataSource-provider(支援下國貨吧:))
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Uncomment and add your base-package here: <context:component-scan base-package="org.springframework.samples.service"/> --> <context:component-scan base-package="com.abel.bigmeter"></context:component-scan> <context:property-placeholder location="classpath:db.properties"></context:property-placeholder> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="initialSize" value="0"></property> <property name="maxActive" value="20"></property> <property name="minIdle" value="0"></property> <property name="maxWait" value="60000"></property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.abel.bigmeter.mapper"></property> </bean> </beans>7. 編寫測試用例,發現kotlin測試用例無法執行,略微修改一下maven-pom.xml檔案吧,新增測試原始檔目錄。
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>src/test/java</sourceDir>
<sourceDir>src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
<configuration>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>
8. 完整的maven-pom.xml檔案:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework.samples.service.service</groupId> <artifactId>bigmeter-server</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <!-- Generic properties --> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!-- Web --> <jsp.version>2.2</jsp.version> <jstl.version>1.2</jstl.version> <servlet.version>2.5</servlet.version> <!-- Spring --> <spring-framework.version>3.2.9.RELEASE</spring-framework.version> <mybatis.version>1.3.0</mybatis.version> <!-- Hibernate / JPA --> <hibernate.version>4.2.1.Final</hibernate.version> <!-- Logging --> <logback.version>1.0.13</logback.version> <slf4j.version>1.7.5</slf4j.version> <!-- Test --> <junit.version>4.12</junit.version> <kotlin.version>1.2.10</kotlin.version> </properties> <dependencies> <!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-framework.version}</version> </dependency> <!-- Other Web dependencies --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>${jsp.version}</version> <scope>provided</scope> </dependency> <!-- Spring and Transactions --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring-framework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-framework.version}</version> </dependency> <!-- Logging with SLF4J & LogBack --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> <scope>compile</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <scope>runtime</scope> </dependency> <!-- Hibernate --> <!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> --> <!-- Test Artifacts --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring-framework.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.abel</groupId> <artifactId>bigmeter-model</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.abel</groupId> <artifactId>bigmeter-webapi</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>2.8.4</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxrs</artifactId> <version>3.1.4.Final</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-client</artifactId> <version>3.1.4.Final</version> </dependency> <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jackson-provider</artifactId> <version>3.1.4.Final</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.3.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.46</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.7.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId> hibernate-validator-annotation-processor </artifactId> <version>6.0.7.Final</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.15</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib-jdk8</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-test</artifactId> <version>${kotlin.version}</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals><goal>add-source</goal></goals> <configuration> <sources> <source>src/main/java</source> <source>src/main/kotlin</source> </sources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-plugin</artifactId> <version>${kotlin.version}</version> <executions> <execution> <id>compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>test-compile</id> <phase>test-compile</phase> <goals> <goal>test-compile</goal> </goals> <configuration> <sourceDirs> <sourceDir>src/test/java</sourceDir> <sourceDir>src/test/kotlin</sourceDir> </sourceDirs> </configuration> </execution> </executions> <configuration> <jvmTarget>1.8</jvmTarget> </configuration> </plugin> </plugins> </build> </project>
9. 簡單的測試用例原始檔,繼承AbstractJUnit4SpringContextTests編寫測試JUnit 4測試用例:
package com.abel.bigmeter.mapper import org.junit.Test import org.junit.runner.RunWith import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.ContextConfiguration import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests import org.springframework.test.context.junit4.SpringJUnit4ClassRunner @RunWith(SpringJUnit4ClassRunner::class) @ContextConfiguration("classpath:spring/application-config.xml") class MapperTest: AbstractJUnit4SpringContextTests() { private val log: Logger = LoggerFactory.getLogger(MapperTest::class.java) @Autowired private var userMapper: UserMapper? = null @Test fun testUserMapper() { log.info("prepare to test UserMapper...") val userList = userMapper?.listUser("1", "%") log.info("User count: ${userList?.count()}") } }