官方网站其实已经介绍的挺详细的了,而且还支持中文版。

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录


说一下比较流行的Spring框架如何集成Mybatis的

先了解下JDBC的数据库操作步骤:

mark

  1. 先将一下代码复制到application.properties文件中(用户名和密码根据数据库账户的实际情况添加),目的是为application.properties增加spring配置数据库链接地址
    spring.datasource.url=jdbc:mysql://localhost:3306/wenda?
     useUnicode=true&characterEncoding=utf8&useSSL=false
     spring.datasource.username=用户名
     spring.datasource.password=密码
     mybatis.config-location=classpath:mybatis-config.xml
     
  2. 在pom.xml中声明要添加的连接mysql数据库和MyBatis框架的Java包,即pom.xml引入mybatis-spring-boot-starter和mysql-connector-java

    <!-- 导入mysql连接的java包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- 导入mybatis框架的java包 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.1.1</version>
    </dependency>
    
  3. 在resources文件夹下添加mybatis-config.xml文件。有没有注意到,第一步中的最后一行代码,它的意思就是导入mybatis-config.xml这个文件,这是mybatis的配置文件。我们现在做的就是导入这个文件。这可以从官网上抄过来,不用记。(这些官网上都讲得很清楚)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?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>

<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/> <!-- 是否缓存(让数据跑得更快) -->
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/> <!-- 请求超时 -->
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/> <!-- 驼峰式命名 -->
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/> <!-- 生成之后要不要返回 -->
</settings>

<!-- Continue going here -->

</configuration>