目錄
一、引言
上篇文章介紹了怎麼在 IntelliJ IDEA 創建Spring Boot項目,這篇文章我們將接着上次創建的Spring Boot項目,介紹Spring Boot如何集成Mybatis,包括 註解 和 Xml配置文件 兩種形式
二、導入jar包
<?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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--用於SpingBoot和Mybatis集成-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!--用於創建MySQL連接-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
三、配置
1、註解方式
包結構:
1)在application.properties中配置MySQL連接信息
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
2)在DemoApplication類上加@MapperScan,該註解的作用是自動去對應的包下掃描Mapper接口文件。
@SpringBootApplication
@MapperScan("com.example.demo.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3)在UserMapper.java中用註解方式編輯SQL
@Service
public interface UserMapper {
@Select("select * from user where id = #{id, jdbcType=INTEGER}")
User selectByPrimaryKey(Integer id);
}
到此,Spring Boot集成Mybatis的註解方式已經完成。
2、XML方式
上面講了基於註解形式的Spring Boot+Mybatis,但是在我們的實際開發中,註解形式並不多見,我們更多的是用XML文件形式,下面我們就來看看XML方式怎麼來實現。
1)在application.properties中配置MySQL連接信息(和註解方式相同,如果已經配置過,跳過此步驟)
2)在Application類上加@MapperScan(和註解方式相同,如果已經配置過,跳過此步驟)
3)在application.properties中配置mapper文件的路徑
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.mapper-locations=classpath:mybatis/mapper/*.xml
4)在UserMapper.java中定義接口
@Service
public interface UserMapper {
List<User> selectAll();
List<User> selectUserByNameAndAge(Map<String, Object> map);
List<User> selectUserByNameList(List<String> nameList);
@Select("select * from user where id = #{id, jdbcType=INTEGER}")
User selectByPrimaryKey(Integer id);
}
5)編輯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.example.demo.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.dao.bean.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<sql id="Base_Column_List">
id, name, age
</sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
</select>
<select id="selectUserByNameList" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
where name in
<foreach collection="list" item="name" index="index" open="(" close=")" separator=",">
#{name, jdbcType=VARCHAR}
</foreach>
</select>
<select id="selectUserByNameAndAge" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
<where>
<if test="name != null and name != ''">
name = #{name, jdbcType=VARCHAR}
</if>
<if test="age != null and age != ''">
and age = #{age, jdbcType=INTEGER}
</if>
</where>
</select>
</mapper>
6)如果想根據自己的需求,定製MyBatis,那麼我們還需要創建mybatis-config.xml(名字不唯一,大家隨意),並在application.properties文件中配置mybatis-config.xml掃描路徑。
mybatis-config.xml:
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 這個配置使全局的映射器啓用或禁用緩存 -->
<setting name="cacheEnabled" value="false" />
<!-- 全局啓用或禁用延遲加載。當禁用時,所有關聯對象都會即時加載 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 當啓用時,有延遲加載屬性的對象在被調用時將會完全加載任意屬性。否則,每種屬性將會按需要加載 -->
<setting name="aggressiveLazyLoading" value="true" />
<!-- 允許或不允許多種結果集從一個單獨的語句中返回(需要適合的驅動) -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 使用列標籤代替列名。不同的驅動在這方便表現不同。參考驅動文檔或充分測試兩種方法來決定所使用的驅動 -->
<setting name="useColumnLabel" value="true" />
<!-- 允許JDBC支持生成的鍵。需要適合的驅動。如果設置爲true則這個設置強制生成的鍵被使用,儘管一些驅動拒絕兼容但仍然有效(比如Derby) -->
<setting name="useGeneratedKeys" value="true" />
<!-- 指定MyBatis如何自動映射列到字段/屬性。PARTIAL只會自動映射簡單,沒有嵌套的結果。FULL會自動映射任意複雜的結果(嵌套的或其他情況) -->
<setting name="autoMappingBehavior" value="PARTIAL" />
<!--當檢測出未知列(或未知屬性)時,如何處理,默認情況下沒有任何提示,這在測試的時候很不方便,不容易找到錯誤。
NONE : 不做任何處理 (默認值)
WARNING : 警告日誌形式的詳細信息
FAILING : 映射失敗,拋出異常和詳細信息
-->
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<!-- 配置默認的執行器。SIMPLE執行器沒有什麼特別之處。REUSE執行器重用預處理語句。BATCH執行器重用語句和批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 設置超時時間,它決定驅動等待一個數據庫響應的時間 -->
<setting name="defaultStatementTimeout" value="25000" />
<!--設置查詢返回值數量,可以被查詢數值覆蓋 -->
<setting name="defaultFetchSize" value="100"/>
<!-- 允許在嵌套語句中使用分頁-->
<setting name="safeRowBoundsEnabled" value="false"/>
<!--是否開啓自動駝峯命名規則映射,即從經典數據庫列名 A_COLUMN 到經典 Java 屬性名 aColumn 的類似映射。-->
<setting name="mapUnderscoreToCamelCase" value="false"/>
<!--MyBatis利用本地緩存機制(Local Cache)防止循環引用(circular references)和加速重複嵌套查詢。 默認值爲 SESSION,這種情況下會緩存一個會話中執行的所有查詢。 若設置值爲 STATEMENT,本地會話僅用在語句執行上,對相同 SqlSession 的不同調用將不會共享數據。-->
<setting name="localCacheScope" value="SESSION"/>
<!-- 當沒有爲參數提供特定的 JDBC 類型時,爲空值指定 JDBC 類型。 某些驅動需要指定列的 JDBC 類型,多數情況直接用一般類型即可,比如 NULL、VARCHAR、OTHER。-->
<setting name="jdbcTypeForNull" value="OTHER"/>
<!-- 指定哪個對象的方法觸發一次延遲加載。-->
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
application.properties:
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.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
四、驗證
各位博友可自行驗證。