Mybatis generator 是一个 Mybatis 插件,可以用于自动生成项目中需要的 pojo 类、对应的 Mapper 接口和 mapper.xml 文件。使用该插件,一方面可以节省开发时间,另一方面也避免手写时打错字的问题。
由于工作需要,我打算在原有的 Spring 项目中使用 Mybatis generator 自动生成代码,以便简化 DAO 层的开发。
闲言少叙,just do it!
1. 引入依赖
a. 父模块配置
<properties> <spring_version>4.3.9.RELEASE</spring_version> <mysql_connector_version>5.1.21</mysql_connector_version> <gson_version>2.2.2</gson_version> <commons_beanutils_version>1.8.3</commons_beanutils_version> <commons_io_version>2.0.1</commons_io_version> <junit_version>4.12</junit_version> <skip_maven_deploy>true</skip_maven_deploy> <lombok.version>1.18.2</lombok.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceOptimize>true</project.build.sourceOptimize> <project.build.sourceDebug>true</project.build.sourceDebug> <project.build.sourceTarget>1.8</project.build.sourceTarget> </properties> <dependencyManagement> <dependencies> <!-- Spring libs --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring_version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring_version}</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons_beanutils_version}</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons_io_version}</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${gson_version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql_connector_version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.ibatis</groupId> <artifactId>ibatis-sqlmap</artifactId> <version>${ibatis_version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.12</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.4</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit_version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> <scope>provided</scope> </dependency> </dependencies> </dependencyManagement>
b. 子模块配置
我们在子模块中引入插件 mybatis-generator-maven-plugin。
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.5</version> <configuration> <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql_connector_version}</version> </dependency> </dependencies> </plugin> </plugins> </build>
2. 引入配置文件
由于上文在 mybatis-generator-maven-plugin 插件中指定了所需的配置文件:generatorConfig.xml,所以在子模块 resources 目录下引入该配置文件。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <context id="baseset" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <commentGenerator> <property name="suppressAllComments" value="false"/> <property name="suppressDate" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://ip:port/db_name" userId="username" password="password"> </jdbcConnection> <!-- 指定生成 pojo 实体类、mybatis映射xml文件、mapper接口的具体位置 --> <javaModelGenerator targetPackage="cn.com.meta.pojo" targetProject="src/main/java"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <javaClientGenerator targetPackage="cn.com.meta.mapper" targetProject="src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!--可以配置多个 table--> <table tableName="t_table_name" domainObjectName="TableNamePojo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <generatedKey column="id" sqlStatement="Mysql" identity="true"/> </table> </context> </generatorConfiguration>
3. 自动生成 Mapper 接口、XML 文件和 pojo 类
点击 IDEA 右侧的 Maven 控件栏,找到对应模块下面的 mybatis-generator 插件,双击即可自动生成 Mapper 接口、mapper.xml 文件和 pojo 类。
4. Spring 中使用 Mapper 接口
a. 配置 spring-meta.xml 文件
<?xml version="1.0" encoding="UTF-8"?> <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" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 使用annotation注解方式配置事务 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 使用JDBC事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 引入配置文件,测试时打开,集成时注释 --> <context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true"/> <!--创建jdbc数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!--测试时打开,集成时注释--> <property name="driverClassName" value="${jdbc.driver}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="10"/> <property name="minIdle" value="10"/> <property name="maxActive" value="200"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="300000"/> <property name="validationQuery" value="SELECT ‘x‘"/> <property name="testWhileIdle" value="true"/> <property name="testOnBorrow" value="false"/> <property name="testOnReturn" value="false"/> <!-- 打开PSCache,并且指定每个连接上PSCache的大小 --> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --> <property name="filters" value="stat"/> </bean> <!-- 配置SqlSessionFactoryBean --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--Mybatis配置文件--> <!--<property name="configLocation" value="classpath:mybatis-mysql.xml"/>--> <!--mapper.xml所在位置--> <property name="mapperLocations"> <list> <value>classpath:mapper/*Mapper.xml</value> </list> </property> <!--需要使用别名的pojo类所在的包--> <property name="typeAliasesPackage" value="cn.com.meta.pojo"/> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.com.meta.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> </beans>
b. config.properties 配置
jdbc.url=jdbc:mysql://ip:port/db_name?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false jdbc.username=username jdbc.password=password jdbc.driver=com.mysql.jdbc.Driver
注意上述的 spring-meta.xml、config.properteis 文件都放在 resources 目录下。
子模块整体结构如下:
c. 接口中新增方法
此时 Mapper 接口已经具备部分 CRUD 的能力,再新增一个自定义的 getNumberWeNeed 方法。
Mapper 接口:
public interface HelloMapper { int deleteByPrimaryKey(String tjId); int insert(Hello record); Hello selectByPrimaryKey(String tjId); List<Hello> selectAll(); // 根据月份、地区查找所需的数值型字段 BigDecimal getNumberWeNeed(@Param("column") String column, @Param("month") String month, @Param("area") String area); }
相应的 XML 文件:
<select id="getNumberWeNeed" resultType="java.math.BigDecimal"> select ${column} from t_table_name where month = #{month} and area= #{area} </select>
5. 编写测试类验证
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-meta.xml"})
public class HelloMapperTest {
@Autowired
HelloMapper helloMapper;
@Test
public void testGetWeNeedNumber(){
// 比较两个 BigDecimal 类型的数必须用 compareTo
Assert.assertTrue(new BigDecimal("2").compareTo(helloMapper.getNumberWeNeed("total", "209905", "BeiJing")) == 0);
}
}
以上。
Spring 中使用 Mybatis generator 自动生成代码
原文:https://www.cnblogs.com/hurricaneyang/p/11180847.html