本節內容:
- 導入逆向工程
- 修改配置文件
- 生成逆向工程代碼
- 測試逆向工程代碼
在之前的例子中,我們得自己手寫pojo和Mapper映射文件(Mapper接口和Mapper.xml文件),如果公司的表比較多,假如有200張表,這手寫起來就很繁瑣了。
使用官方網站的Mapper自動生成工具mybatis-generator-core-1.3.2來生成po類和Mapper映射文件。注意這些Mapper文件只針對單表操作,涉及多表的操作得自己手寫。
一、導入逆向工程
導入IDEA后,項目如下所示:
看上面的lib下的jar包,里面有連接mysql的驅動包,也有連接oracle的驅動包,我這里連接的是mysql數據庫。
二、修改配置文件
generatorConfig-base.xml和generatorConfig-business.xml這兩個配置文件沒用,可以刪除掉。修改generatorConfig.xml:
注意修改以下幾點:
- 修改要生成的數據庫表
- pojo文件所在包路徑
- Mapper所在的包路徑
<?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="testTables" targetRuntime="MyBatis3"> <commentGenerator> <!-- 是否去除自動生成的注釋(生成的注釋是英文的) true:是 : false:否 --> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--數據庫連接的信息:驅動類、連接地址、用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="123456"> </jdbcConnection> <!--連接oracle數據庫--> <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver" connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" userId="yycg" password="yycg"> </jdbcConnection> --> <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer,為 true時把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- targetProject:生成PO類的位置 要注意targetProject,如果你是在Linux或者Mac上,路徑應該是./src,如果是在windows上,路徑應該是.\src--> <javaModelGenerator targetPackage="com.wisedu.mybatis.model" targetProject="./src"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> <!-- 從數據庫返回的值被清理前后的空格 --> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.wisedu.mybatis.dao.automatic.mapper" targetProject="./src"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.wisedu.mybatis.dao.automatic.mapper" targetProject="./src"> <!-- enableSubPackages:是否讓schema作為包的后綴 --> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <!-- 指定數據庫表 --> <table schema="" tableName="user"> <!--生成的pojo類的屬性名和表的列名一致,默認是遇到下划線變駝峰的。比如表中有一列叫user_id,那么默認生成的類屬性名是userId--> <property name="useActualColumnNames" value="true"/> </table> <table schema="" tableName="orders"> <property name="useActualColumnNames" value="true"/> </table> <!-- 有些表的字段需要指定java類型 <table schema="" tableName=""> <columnOverride column="" javaType="" /> </table> --> </context> </generatorConfiguration>
三、生成逆向工程代碼
執行主程序 GeneratorSqlmap.java 的main方法:
查看控制台日志:
2017-12-28 17:55:14,738 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Retrieving column information for table "user" 2017-12-28 17:55:14,772 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "id", data type 4, in table "mybatis..user" 2017-12-28 17:55:14,772 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "username", data type 12, in table "mybatis..user" 2017-12-28 17:55:14,773 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "birthday", data type 91, in table "mybatis..user" 2017-12-28 17:55:14,773 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "sex", data type 1, in table "mybatis..user" 2017-12-28 17:55:14,773 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "address", data type 12, in table "mybatis..user" 2017-12-28 17:55:14,783 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Retrieving column information for table "orders" 2017-12-28 17:55:14,790 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "id", data type 4, in table "mybatis..orders" 2017-12-28 17:55:14,790 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "user_id", data type 4, in table "mybatis..orders" 2017-12-28 17:55:14,791 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "number", data type 12, in table "mybatis..orders" 2017-12-28 17:55:14,791 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "createtime", data type 93, in table "mybatis..orders" 2017-12-28 17:55:14,791 [main] DEBUG [org.mybatis.generator.internal.db.DatabaseIntrospector] - Found column "note", data type 12, in table "mybatis..orders" Process finished with exit code 0
查看工程,就可以看見代碼生成了。如果沒生成,請刷新下項目。
【說明】:
關於model中的 OrdersExample.java 和 UserExample.java 是專門的條件對象。下面的測試中會有使用。
四、測試逆向工程代碼
項目結構和前面博客中的一樣,只是model、mapper都是上面逆向工程生成的代碼。
applicationContext.xml內容如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 加載配置文件 --> <context:property-placeholder location="classpath:/config/db.properties" /> <!-- 數據庫連接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="10" /> <property name="maxIdle" value="5" /> </bean> <!-- 配置Mybatis的工程 SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 配置mybatis核心配置文件,原來核心配置文件中是有連接池的,現在交給Spring了 --> <property name="configLocation" value="classpath:/config/sqlMapConfig.xml" /> <!-- 配置數據源 --> <property name="dataSource" ref="dataSource" /> </bean> <!-- Mapper代理的方式開發方式二,掃描包方式配置代理(不注入工廠也可以,org.mybatis.spring.mapper.MapperScannerConfigurer會自己去Spring容器中去找) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 配置Mapper接口 --> <property name="basePackage" value="com.wisedu.mybatis.dao.automatic.mapper" /> </bean> </beans>
sqlMapConfig.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> <!-- 設置別名 --> <typeAliases> <!-- 2. 指定掃描包,會把包內所有的類都設置別名,別名的名稱就是類名,大小寫不敏感 --> <package name="com.wisedu.mybatis.model" /> </typeAliases> <mappers> <package name="com.wisedu.mybatis.dao.automatic.mapper" /> </mappers> </configuration>
測試類MapperTest.java:
package com.wisedu.mybatis.test; import com.wisedu.mybatis.dao.automatic.mapper.UserMapper; import com.wisedu.mybatis.model.User; import com.wisedu.mybatis.model.UserExample; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.Date; import java.util.List; /** * Created by jkzhao on 12/28/17. */ public class MapperTest { private ApplicationContext context; @Before public void setUp() throws Exception { this.context = new ClassPathXmlApplicationContext("classpath:/config/applicationContext.xml"); } @Test public void testQueryUser() { // 獲取Mapper UserMapper userMapper = this.context.getBean(UserMapper.class); // 創建User對象擴展類,用戶設置查詢條件 UserExample example1 = new UserExample(); example1.createCriteria().andUsernameLike("%王%"); //example.createCriteria() 創建一個內部類對象 // 查詢數據 List<User> list = userMapper.selectByExample(example1); System.out.println(list.size()); UserExample example2 = new UserExample(); example2.createCriteria().andUsernameLike("%張%").andSexEqualTo("1"); int countByExample = userMapper.countByExample(example2); System.out.println(countByExample); //通過主鍵查詢用戶 User user = userMapper.selectByPrimaryKey(1); System.out.println(user); } @Test public void testInsert() { // 獲取Mapper UserMapper userMapper = this.context.getBean(UserMapper.class); User user = new User(); user.setUsername("諸葛亮"); user.setSex("1"); user.setBirthday(new Date()); user.setAddress("三國"); userMapper.insert(user); } }
【注意】:如果需要查看生成的sql語句,需要將log4j.properties放在src目錄下。因為log4j.jar查找文件的時候是 先去代碼根目錄下去找log4j.properties,src運行后的發布目錄就是代碼根目錄。可以直接修改log4j的源代碼,或者修改web.xml中的配置:
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.properties</param-value> </context-param>
或者
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.xml</param-value> </context-param>
【總結】:
- 逆向工程生成的代碼只能做單表查詢
- 不能在生成的代碼上進行擴展,因為如果數據庫變更,需要重新使用逆向工程生成代碼,原來編寫的代碼就被覆蓋了。
- 一張表會生成4個文件