前言
最近開始了SpringBoot相關知識的學習,作為為目前比較流行、用的比較廣的Spring框架,是每一個Java學習者及從業者都會接觸到一個知識點。作為Spring框架項目,肯定少不了與數據庫持久層的整合。我們在學習Java初始就被灌輸SSM框架(Spring、SpringMVC、Mybatis),我們大概也只是知道Mybatis是與數據庫打交道的,但這也只是名詞上的理解。
Mybatis具體是什么?
MyBatis 是一款優秀的持久層框架,它支持自定義 SQL、存儲過程以及高級映射。MyBatis 免除了幾乎所有的 JDBC 代碼以及設置參數和獲取結果集的工作。MyBatis 可以通過簡單的 XML 或注解來配置和映射原始類型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 對象)為數據庫中的記錄。
。。。。。。
這里我就不廢話介紹了,詳細的看官方文檔地址:https://mybatis.org/mybatis-3/zh/index.html
到后來開始完整的學習Mybatis、到Spring、SpringMVC、再到SpringBoot都有它的身影,它的使用及配置越來越簡單方便,可能出現這種情況,學到SpringBoot整合Mybatis發現,為什么要這么操作?為什么要寫這個注解?為什么要添加掃描包配置?那么這篇文章就是將開始學習Mybatis到現在SpringBoot整合Mybatis的知識串起來,加深印象增加理解。
下面是我往期關於Mybatis知識點的博客,有興趣的可以看一下。
首先我也是作為Java的一名初學者,下面文章也是按照從JDBC、Mybatis、Spring、SpringMVC、再到SpringBoot的思路編寫,也是我自己的學習路線中Mybatis由繁到簡的過程。大致分為五個階段,可能后面幾個階段內容可以合並為一個階段,我為了體現Mybatis使用的方便簡化,從而作為一個階段。也可以幫助那些直接學習SpringBoot的同學理解整合Mybatis的遞進過程。如果其中有錯誤之處,也煩請各位大佬給予指正!感謝!
階段一:JDBC
我們在學習Mybatis之前,我們使用JDBC即數據庫連接驅動進行數據庫連接操作。
其大致操作步驟:
- 加載驅動
com.mysql.cj.jdbc.Driver
- 設置數據庫用戶名、密碼及URL
- 使用
DriverManager.getConnection(url, userName, passWord)
創建數據庫對象 - 創建執行Sql對象
connection.createStatement()
- 通過statement對象執行具體的Sql
statement.executeQuery(sql)
- 最后關閉釋放連接
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1.加載驅動(固定寫法)
Class.forName("com.mysql.cj.jdbc.Driver");// 注意加載新的驅動,舊的棄用了
// 2.用戶信息和url
String url = "jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSl=true";// 注意添加時區參數
String userName = "root";
String passWord = "970628";
// 3.連接成功,數據庫對象
Connection connection = DriverManager.getConnection(url, userName, passWord);
// 4.執行sql的對象
Statement statement = connection.createStatement();
// 5.執行sql
String sql= "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("name="+resultSet.getObject("name"));
}
// 6.釋放鏈接
resultSet.close();
statement.close();
connection.close();
}
JDBC的一些問題:
- 數據庫鏈接創建、釋放頻繁造成系統資源浪費從而影響系統性能
- Sql語句變動比較大,每次變動都需要改動Java代碼
- 每個一業務需要編寫大量重復的JDBC代碼,不宜維護
階段二:Mybatis入門
Mybatis對jdbc的操作數據庫的過程進行封裝,使開發者只需要關注 SQL 本身,而不需要花費精力去處理例如注冊驅動、創建connection、創建statement、手動設置參數、結果集檢索等jdbc繁雜的過程代碼。
其大致步驟:
- 首先導入MyBatis jar包
- 建立 mybatis-config.xml 的核心配置文件
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=True"/>
<property name="username" value="root"/>
<property name="password" value="970628"/>
</dataSource>
</environment>
</environments>
</configuration>
- 通過mybatis環境等配置信息構造SqlSessionFactory即會話工廠,階段一中創建數據庫連接等操作都交給sqlSessionFactory來操作
- 由會話工廠創建sqlSession即會話,操作數據庫需要通過sqlSession進行,類似於我們階段一中statement對象
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
// 獲取sqlSessionFactory對象
String resource="mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
// 既然有了 SqlSessionFactory,顧名思義,我們可以從中獲得 SqlSession 的實例。
// SqlSession 提供了在數據庫執行 SQL 命令所需的所有方法。你可以通過 SqlSession 實例來直接執行已映射的 SQL 語句
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
- 創建POJO對應的Mapper接口及對應的Mapper.xml文件。我們在階段一需要寫Mapper的實現類,需要大量的JDBC操作代碼,這里我們通過Mapper.xml文件實現,滿足SqlSession的調用。
public interface StudentMapper {
// 查詢全部學生
List<Student> getStudentList();
// 根據id查詢學生
Student getStudentById(int id);
// 插入一個學生
int addUser(Student student);
}
<?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">
<!--這里的namespace要與dao下的Mapper名稱一一對應-->
<mapper namespace="com.tioxy.dao.StudentMapper">
<!--id對應的是Mapper接口中對應的方法-->
<!--resultType是SQL語句的返回值-->
<!--parameterType參數類型-->
<select id="getStudentList" resultType="com.tioxy.pojo.Student">
select * from school.student
</select>
<select id="getStudentById" resultType="com.tioxy.pojo.Student" parameterType="int">
select * from school.student where id = #{id}
</select>
<insert id="addUser" parameterType="com.tioxy.pojo.Student" >
insert into school.student (id,name,password,sex,birthd,address,email) values (#{id},#{name},#{password},#{sex},#{birthd},#{address},#{email});
</insert>
</mapper>
- 在核心配置文件中注冊Mapper,目的需要告訴 MyBatis 到哪里去找到這些執行Sql語句
<!--每一個Mapper.xml文件都需要在mybatis核心配置文件中注冊-->
<mappers>
<mapper resource="com/tioxy/dao/StudentMapper.xml"/>
</mappers>
- 通過
sqlSession.getMapper()
獲取接口對應的執行方法及結果 - 關閉連接
public void test(){
// 第一步,獲取sqlSession對象
SqlSession sqlSession= MybatisUtils.getSqlSession();
try {
// 方式一,getMapper
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudentList();
for (Student student : studentList) {
System.out.println(student);
}
}catch (Exception e){
e.printStackTrace();
}finally {
// 關閉sqlSession
sqlSession.close();
}
}
階段三:Spring中整合MyBatis
MyBatis-Spring 會幫助你將 MyBatis 代碼無縫地整合到 Spring 中。它將允許 MyBatis 參與到 Spring 的事務管理之中,創建映射器 mapper 和 SqlSession 並注入到 bean 中,以及將 Mybatis 的異常轉換為 Spring 的 DataAccessException。最終,可以做到應用代碼不依賴於 MyBatis,Spring 或 MyBatis-Spring。
大致步驟如下:
- 導入
mybatis-spring
依賴包 - 在Spring xml文件中通過Spring的數據源
DriverManagerDataSource
替換階段二中Mybatis的數據源
<!--DataSources:使用Spring的數據源替換Mybatis的配置
這里使用Spring提供的JDBC
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=True"/>
<property name="username" value="root"/>
<property name="password" value="970628"/>
</bean>
- 構建
SqlSessionFactoryBean
,在第二階段Mybatis入門的學習中,需要構建 SqlSessionFactory 通過 SqlSessionFactory 構建 SqlSession 進行數據庫的操作CURD。我們這里使用SqlSessionFactoryBean來創建 SqlSessionFactory,在Spring 的 XML 配置如下
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
- 同階段二編寫POJO類及Mapper接口及Mapper.xml文件並在配置文件中注冊Mapper
- 與基礎的 MyBatis 不同的是,需要創建Mapper接口的實現類,並繼承
SqlSessionDaoSupport
,目的是不需要管理SqlSession,而且對事務的支持更加友好
import com.tioxy.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectUser() {
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
- 注冊實現類的bean,並關聯 sqlSessionFactory
<bean id="userMapper2" class="com.tioxy.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
- 通過
ApplicationContext
的 getBean()方法獲取接口並執行方法並返回結果。
public void selectUserTest() throws IOException {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
其中第5步,原理是內置使用了 SqlSessionTemplate
,SqlSessionTemplate
是 MyBatis-Spring 的核心。作為 SqlSession 的一個實現,這意味着可以使用它無縫代替你代碼中已經在使用的 SqlSession。SqlSessionTemplate
是線程安全的,可以被多個 DAO 或映射器所共享使用。構建 SqlSessionTemplate
是 Spring學習之Spring與Mybatis的兩種整合方式 中的第一種整合方式,本文章使用第二種方式。
總的來說,就是 Mybatis 的操作被Spring接管,通過一個個Spring Bean來實現持久層操作。
階段四:SSM中整合MyBatis
其實有的小伙伴在這一階段已經開始使用注解方式進行Mybatis操作,我這里為了說明Mybatis的整個演進過程,使用配置方式說明
在這一階段與第三階段中使用Mybatis並沒有很大的差別,前四步與第三階段相同,其最大的改進是在Spring注冊bean MapperScannerConfigurer
,其最大的作用是通過反射的方式自動的幫我們構造Mapper的實現類,省去我們手動編寫。
<!--配置dao接口掃描包,動態的實現Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入 sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要掃描的包-->
<property name="basePackage" value="com.tioxy.mapper"/>
</bean>
接下來就是通過Service層調用來實現具體的業務。
所以這一階段與階段三並沒有太大的差別與提升。可能有的小伙伴說,這一階段使用階段三也是可以的,的確如此。其實對於我來說,可能這一階段使用了 MapperScannerConfigurer
,算作上一階段的簡化,所以拿出作為階段四,同理,我將使用注解的方式作為第四階段的簡化,所以放作下一階段五。
階段五:SpringBoot整合MyBatis
在這一階段使用注解進行開發,大大簡化了各項配置,使得更加專注於業務及Sql的操作,避免了大量繁瑣的配置。
大致步驟:
- 導入mybatis的啟動器
mybatis-spring-boot-starter
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
- 在 application.yaml 文件中配置數據源,同前幾階段在xml中配置數據源一樣
spring:
datasource:
username: root
password: 970628
url: jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
- 編寫POJO類及Mapper接口及Mapper.xml文件並在配置文件中添加Mapper.xml的掃描配置
# 整合Mybatis
mybatis:
# 別名
type-aliases-package: com.tioxy.pojo
# 原來dao與mapper.xml在同一路徑,現在不在同一路徑需要設置下面的參數,目的就是告訴*.xml文件的路徑
mapper-locations: classpath:mybatis/mapper/*.xml
在前階段的構建 SqlSessionFactoryBean
以及 SqlSession
全都由Spring幫我們實現,所以這里我們省去了這幾項配置,只需在Mapper接口上添加@Mapper
注解,表示了這是一個 mybatis 的mapper 類,由Spring幫我們設置,而且也省去了階段四種使用 MapperScannerConfigurer
來創建Mapper對應的接口
這里我使用Mapper.xml編寫SQL語句,也可以使用注解方式,兩種方式都可以,看個人喜好。我選擇xml文件的原因是編寫SQL語句靈活、擴展性好
如果使用注解方式編寫Sql,則不需要Mapper.xml文件,也不要設置Mapper.xml的掃描配置,直接在接口的方法中使用 @Select
、@Insert
等注解
@Mapper
@Repository
public interface UserMapper {
/**
* 查詢所有的用戶
* @return
*/
@Select("select * from User")
List<User> queryUserList();
}
這里面 @Repository
,是告訴Spring,這是一個Spring組件,類似於 @Controller
、@Service
一樣
如果不想在每個方法中都加上 @Mapper
注解,可以直接在SpringBoot主啟動類上添加 @MapperScan
注解
@SpringBootApplication
@MapperScan("com.tioxy.mapper")
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
- 最后就是通過
@Autowired
自動裝配,獲取接口的各個業務方法進行持久層操作
總結
通過一個個階段的演進,從一開始JDBC,手動創建數據庫連接,創建 statement
執行Sql,這種方式,頻繁打開關閉數據庫,且Sql與Java代碼耦合度高,修改Sql需要修改Java代碼,很不方便,於是通過Mybatis進行封裝,在單獨的xml文件種統一編寫Sql,大大簡化了操作。Mybatis在不同階段隨着Spring的演進,也在逐漸簡化了各種繁瑣的配置,以及到最后的SpringBoot中,不再需要手動創建 SqlSessionFactoryBean
、SqlSession
以及Mapper的實現類,通過注解操作,使得更加專注於業務及Sql的編寫。當然在Java的體系中,持久化框架不只是Mybatis,還有Hibernate、TopLink、dbutils、Spring Data,其大致原理相似,這就需要根據實際開發及個人習慣進行選擇。
編寫不易,轉載請注明出處
如有不當之處,感謝指正!