在做springboot+mybatis整合中,我們可以通過mybatis自帶的mybatis-generator插件自動生成代碼,這裡有個前提,就是需要在資料庫中先生成表,然後根據表來生成實體和dao層代碼,以及mybatis的映射檔案。
這裡介紹如何在idea中,通過配置,一步一步實作代碼生成。
1、建構maven工程,修改pom.xml,配置mybatis依賴,以及mybatis-generator插件。
2、設定mapper映射檔案生成的位址:application.properties中增加配置。
3、建構資料庫以及表結構。
4、設定自動生成代碼配置檔案。
5、建構maven任務,執行建構。
6、利用建構的結果測試。
===========================================================================
第一步:pom.xml檔案内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<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>com.xxx.mybatis</groupId>
<artifactId>mybatis-generate</artifactId>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>mybatis generator</id>
<phase>package</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
<configurationFile>
src/main/resources/mybatis-generator.xml
</configurationFile>
</configuration>
</plugin>
</plugins>
</build>
</project>
第二步:在resources目錄下,建立配置檔案application.properties,并設定mybatis映射檔案生成的位址
server.port=9080
mybatis.mapperLocations=classpath:mapper/*.xml
第三步:準備資料庫(mybatis)以及表結構
user_info
mysql> desc user_info;
+----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(64) | NO | | NULL | |
| gender | tinyint(4) | NO | | NULL | |
| age | int(11) | NO | | NULL | |
| mobile | varchar(11) | NO | | NULL | |
| register_mode | varchar(10) | NO | | NULL | |
| third_party_id | varchar(255) | NO | | NULL | |
+----------------+--------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
user_password
mysql> desc user_password;
+-----------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| encrpt_password | varchar(255) | NO | | NULL | |
| user_id | int(11) | NO | | NULL | |
+-----------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
第四步:配置代碼自動生成配置檔案,這裡需要指定連接配接資料庫,生成實體和dao的位置,以及表與實體的映射關系。
<?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="DB2Tables" targetRuntime="MyBatis3">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="hadoop"
password="hadoop">
</jdbcConnection>
<javaModelGenerator targetPackage="com.xxx.mybatis.domain" 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 type="XMLMAPPER" targetPackage="com.xxx.mybatis.dao"
targetProject="src/main/java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="user_info" domainObjectName="User"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
<table tableName="user_password" domainObjectName="UserPassword"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
table中 enableCountByExample=false,enableUpdateByExample=false,enableDeleteByExample=false,enableSelectByExample
=false,selectByExampleQueryId=false,生成的dao的方法中,可以去掉一些跟Example相關的複雜方法,一般的複雜查詢,我們可以自己手動編寫。
第五步:建構:IDEA上點選Edit Configurations->建立Maven->填寫工程目錄working directory以及Command line:mybatis-generator:generate。接着就可以建構了。
建構以及建構之後生成的檔案:
建構成功列印資訊如下:
[INFO] Introspecting table user_info
[INFO] Introspecting table user_password
[INFO] Generating Record class for table user_info
[INFO] Generating Mapper Interface for table user_info
[INFO] Generating SQL Map for table user_info
[INFO] Generating Record class for table user_password
[INFO] Generating Mapper Interface for table user_password
[INFO] Generating SQL Map for table user_password
[INFO] Saving file UserMapper.xml
[INFO] Saving file UserPasswordMapper.xml
[INFO] Saving file User.java
[INFO] Saving file UserMapper.java
[INFO] Saving file UserPassword.java
[INFO] Saving file UserPasswordMapper.java
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.793 s
[INFO] Finished at: 2018-12-11T11:00:42+08:00
[INFO] Final Memory: 15M/305M
[INFO] ------------------------------------------------------------------------
第六步:根據生成的代碼,驗證mybatis與springboot整合。第二步中的配置檔案application.properties做修改,增加資料庫連接配接資訊。
server.port=9080
mybatis.mapperLocations=classpath:mapper/*.xml
spring.datasource.name=mybatis
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false
spring.datasource.username=hadoop
spring.datasource.password=hadoop
spring.datasource.type=com.zaxxer.hikari.HikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
采用資料庫連接配接池:HikariCP,這裡配置的資料庫資訊是給系統使用的,之前在mybatis-generator.xml中配置的資料庫資訊是給代碼生成器使用的。
com.xxx.mybatis目錄下建立App.java
package com.xxx.mybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.xxx.mybatis.dao")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
建立com.xxx.mybatis.controller包,并在其下建立UserController.java
package com.xxx.mybatis.controller;
import com.xxx.mybatis.dao.UserMapper;
import com.xxx.mybatis.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/get")
@ResponseBody
public String get(){
User user = userMapper.selectByPrimaryKey(1);
if(user==null){
return "user is not present.";
}
return user.getName();
}
}
啟動App.java類,并通路http://localhost:9080/user/get,資料庫表user_info中增加一條id=1的記錄,再次通路。
至此,mybatis-generator插件自動生成代碼的示例就完成了,一般的開發中,基本都是先有實體,再有表,而且複雜查詢會随着業務的複雜越來越多,僅僅靠插件是無法滿足的,這個示例就當學習練手了。