本文介紹如何將Maven和Mybatis-Generator配合使用。html
Mybatis-Generator是Mybatis提供的一個便捷型插件,自動能夠爲項目生產對應的實體類,Mapper,dao層。java
官網文檔:www.mybatis.org/generator/i…mysql
本文使用SpringBoot結合Mybatis-Generator插件使用,數據庫Mysql。git
新建一個SpringBoot項目。web
在項目pom文件中,引入Mybatis-Generator插件,而且引入Mybatis和Mysql依賴。完整pom代碼以下:spring
<?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.dalaoyang</groupId>
<artifactId>springboot_generator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_generator</name>
<description>springboot_generator</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.15.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>mybatis-generator</id>
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- Mybatis-Generator 工具配置文件的位置 -->
<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<classifier>exec</classifier>
</configuration>
</plugin>
</plugins>
</build>
</project>
複製代碼
在pom文件中配置的Mybatis-Generator 工具配置文件的位置新建一個generatorConfig.xml,(本文案例配置的位置是src/main/resources/mybatis-generator/generatorConfig.xml),配置文件代碼以下,具體配置須要自行修改至本身的項目:sql
<?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>
<!--執行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
<!-- 引入配置文件 -->
<properties resource="application.properties"/>
<!--classPathEntry:數據庫的JDBC驅動,換成你本身的驅動位置 可選 -->
<!--<classPathEntry location="D:\generator_mybatis\mysql-connector-java-5.1.24-bin.jar" /> -->
<!-- 一個數據庫一個context -->
<!--defaultModelType="flat" 大數據字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 自動識別數據庫關鍵字,默認false,若是設置爲true,根據SqlReservedWords中定義的關鍵字列表;
通常保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋 -->
<property name="autoDelimitKeywords" value="true" />
<!-- 生成的Java文件的編碼 -->
<property name="javaFileEncoding" value="utf-8" />
<!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,好比ORACLE就是雙引號,MYSQL默認是`反引號; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<!-- 格式化java代碼 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代碼 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 註釋 -->
<commentGenerator >
<property name="suppressAllComments" value="false"/><!-- 是否取消註釋 -->
<property name="suppressDate" value="true" /> <!-- 是否生成註釋代時間戳-->
</commentGenerator>
<!-- jdbc鏈接 -->
<jdbcConnection driverClass="${spring.datasource.driver-class-name}" connectionURL="${spring.datasource.url}" userId="${spring.datasource.username}" password="${spring.datasource.password}" />
<!-- 類型轉換 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自動轉化如下類型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成實體類地址 -->
<javaModelGenerator targetPackage="com.dalaoyang.entity" targetProject="${mybatis.project}" >
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="${mybatis.resources}" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml對應client,也就是接口dao -->
<javaClientGenerator targetPackage="com.dalaoyang.dao" targetProject="${mybatis.project}" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- table能夠有多個,每一個數據庫中的表均可以寫一個table,tableName表示要匹配的數據庫表,也能夠在tableName屬性中經過使用%通配符來匹配全部數據庫表,只有匹配的表纔會自動生成文件 -->
<table tableName="user" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 數據庫表主鍵 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
</table>
<table tableName="book" enableCountByExample="true" enableUpdateByExample="true" enableDeleteByExample="true" enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 數據庫表主鍵 -->
<generatedKey column="id" sqlStatement="Mysql" identity="true" />
</table>
</context>
</generatorConfiguration>
複製代碼
配置項目的application.properties,其中數據庫信息,Mapper地址以前都有過介紹,具體SpringBoot-Mybatis配置能夠參考: 《SpringBoot+Mybatis+MySql學習》數據庫
本文配置以下:apache
## mapper xml 文件地址
mybatis.mapper-locations=classpath*:mapper/*Mapper.xml
##數據庫url
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false
##數據庫用戶名
spring.datasource.username=root
##數據庫密碼
spring.datasource.password=123456
##數據庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#Mybatis Generator configuration
#dao類和實體類的位置
mybatis.project =src/main/java
#mapper文件的位置
mybatis.resources=src/main/resources
複製代碼
到這裏其實配置就完成了,能夠體驗Mybatis-Generator插件的優勢了,在右側Maven處點擊如圖所示位置,如圖:api
點擊完成後,能夠看到Mapper,dao,實體類都已經建立好了,如圖:
建立完成會給我生成幾個默認的建當方法,如UserMapper代碼以下:
package com.dalaoyang.dao;
import com.dalaoyang.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
public interface UserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
int insert(User record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
User selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
List<User> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user
*
* @mbggenerated
*/
int updateByPrimaryKey(User record);
}
複製代碼
UserMapper.xml代碼以下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.dalaoyang.dao.UserMapper" >
<resultMap id="BaseResultMap" type="com.dalaoyang.entity.User" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<id column="id" property="id" jdbcType="BIGINT" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="user_password" property="userPassword" jdbcType="VARCHAR" />
</resultMap>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
delete from user
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" parameterType="com.dalaoyang.entity.User" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
<selectKey resultType="java.lang.Long" keyProperty="id" order="AFTER" >
SELECT LAST_INSERT_ID()
</selectKey>
insert into user (user_name, user_password)
values (#{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR})
</insert>
<update id="updateByPrimaryKey" parameterType="com.dalaoyang.entity.User" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
update user
set user_name = #{userName,jdbcType=VARCHAR},
user_password = #{userPassword,jdbcType=VARCHAR}
where id = #{id,jdbcType=BIGINT}
</update>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select id, user_name, user_password
from user
where id = #{id,jdbcType=BIGINT}
</select>
<select id="selectAll" resultMap="BaseResultMap" >
<!--
WARNING - @mbggenerated
This element is automatically generated by MyBatis Generator, do not modify.
-->
select id, user_name, user_password
from user
</select>
</mapper>
複製代碼
在UserMapper上加入註解@Mapper代表是持久化映射層,啓動類上加入註解@RestController進行測試,這裏簡單調用一個查詢全部的方法selectAll,啓動類代碼以下:
@SpringBootApplication
@RestController
public class SpringbootGeneratorApplication {
@Autowired
private UserMapper userMapper;
@GetMapping("/findAll")
public List<User> findAll(){
return userMapper.selectAll();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootGeneratorApplication.class, args);
}
}
複製代碼
運行項目,瀏覽器訪問localhost:8080/findAll如圖所示:
源碼下載 :大老楊碼雲