在本地MySQL數(shù)據(jù)庫中創(chuàng)建了一個air_conditioner數(shù)據(jù)庫钞艇,只有一個devices表,這個表包含三個字段:device_id私沮、type始赎、position,本文將嘗試訪問這個數(shù)據(jù)庫仔燕。創(chuàng)建數(shù)據(jù)庫的腳本放在文末給出的git中了造垛。
1、pom文件加入mybatis依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.2.0</version>
</dependency>
2晰搀、pom文件加入mybatis generator插件配置
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<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.35</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
3五辽、編寫配置文件generatorConfig.xml
這個文件定義了mybatis generator如何生成model、dao外恕、mapper杆逗,詳見官方文檔。把這個文件存放在步驟2中指定的位置:src/main/resources/mybatis-generator/
<?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>
<!-- 引入配置文件 -->
<properties resource="mybatis-generator/mybatisGeneratorinit.properties"/>
<!--classPathEntry:數(shù)據(jù)庫的JDBC驅(qū)動,換成你自己的驅(qū)動位置 可選 -->
<!--<classPathEntry location="D:\generator_mybatis\mysql-connector-java-5.1.24-bin.jar" /> -->
<!-- 一個數(shù)據(jù)庫一個context -->
<!--defaultModelType="flat" 大數(shù)據(jù)字段鳞疲,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="autoDelimitKeywords" value="true" />
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<property name="javaFileEncoding" value="utf-8" />
<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="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" />
<!-- 類型轉(zhuǎn)換 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal罪郊, false可自動轉(zhuǎn)化以下類型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成實體類地址 -->
<javaModelGenerator targetPackage="com.quiterr.model" targetProject="${project}" >
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mappers" targetProject="${resources}" >
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml對應client,也就是接口dao -->
<javaClientGenerator targetPackage="com.quiterr.dao" targetProject="${project}" type="XMLMAPPER" >
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<table tableName="devices" 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>
4尚洽、編寫mybatisGeneratorinit.properties
這個文件保存了一些generatorConfig.xml會用到的配置信息悔橄,比如項目的目錄、數(shù)據(jù)庫的連接信息腺毫,這些信息也可以直接放在generatorConfig.xml中癣疟,但這樣可讀性差一些。
#Mybatis Generator configuration
project =src/main/java
resources=src/main/resources
jdbc_driver =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/air_conditioner
jdbc_user=root
jdbc_password=123456
5潮酒、生成dao睛挚、model、mapper文件
在數(shù)據(jù)庫建好之后急黎,在編寫業(yè)務代碼之前扎狱,就該生成這些文件了侧到,在maven的生命周期里似乎沒有一個合適的階段用來執(zhí)行這個操作。其實只需要在CMD中運行一行命令即可:
call mvn mybatis-generator:generate -e
6委乌、配置dao床牧、mapper的路徑
a荣回、配置dao的路徑
可以在生成的每個dao文件里添加@mapper注解遭贸,如:
@Mapper
public interface DevicesMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table devices
*
* @mbggenerated
*/
int countByExample(DevicesExample example);
//后邊的代碼省略
也可以在App類添加@MapperScan注解,如:
@SpringBootApplication
@EnableScheduling
@MapperScan("com.quiterr.dao")
@EnableConfigurationProperties({AirConditionerSettings.class})
public class App {
public static void main(String args[]){
SpringApplication.run(App.class);
}
}
b心软、配置mapper的路徑
在application.properties里加一行:
mybatis.mapper-locations=classpath:mappers/*.xml
ps:model的路徑不用配置壕吹,在mapper文件里面已有
7、訪問數(shù)據(jù)庫
在model目錄下删铃,mybatis generator為每一個表生成了一個example文件耳贬,通過這個文件提供了一種“面向?qū)ο蟆钡臄?shù)據(jù)庫查詢,總之不用自己寫sql語句了猎唁。
//mybatis generator生成的example文件
public class DevicesExample {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table devices
*
* @mbggenerated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table devices
*
* @mbggenerated
*/
protected boolean distinct;
//后面的代碼省略
要查詢數(shù)據(jù)庫咒劲,首先,注入dao:
@Autowired
DevicesMapper devicesMapper;
然后像這樣:
//從數(shù)據(jù)庫查詢各類設備的數(shù)量
String pos="機房";
DevicesExample devicesExample = new DevicesExample();
DevicesExample.Criteria criteria = devicesExample.createCriteria();
criteria.andPositionEqualTo(pos);
List<Devices> deviceList = devicesMapper.selectByExample(devicesExample);
本文源碼:https://github.com/quiterr/mybatis-generator-test.git
官方文檔:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/