歡迎大家回到《 Java教程之Spring30天快速入門》,本教程所有示例均基于Maven實現(xiàn),如果您對Maven還很陌生,請移步本人的博文《 如何在windows11下安裝Maven并配置以及 IDEA配置Maven環(huán)境》,本文的上一篇為《 IOC/DI注解開發(fā)管理第三方bean》
學習到這里,已經(jīng)對Spring有一個簡單的認識了,Spring有一個容器,叫做IoC容器,里面保存bean。在進行企業(yè)級開發(fā)的時候,其實除了將自己寫的類讓Spring管理之外,還有一部分重要的工作就是使用第三方的技術(shù)。前面已經(jīng)講了如何管理第三方bean了,下面結(jié)合IoC和DI,整合Mybatis,進一步加深對Spring的使用理解。
1 Spring整合Mybatis思路分析
1.1 環(huán)境準備
在準備環(huán)境的過程中,我們也來回顧下Mybatis開發(fā)的相關(guān)內(nèi)容:
1.1.1 步驟1:準備數(shù)據(jù)庫表
Mybatis是來操作數(shù)據(jù)庫表,所以先創(chuàng)建一個數(shù)據(jù)庫及表
create database spring_db character set utf8;
use spring_db;
create table tbl_account(
id int primary key auto_increment,
name varchar(35),
money double
);
1.1.2 步驟2:創(chuàng)建項目導入jar包
項目的pom.xml添加相關(guān)依賴
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
1.1.3 步驟3:根據(jù)表創(chuàng)建模型類
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
//setter...getter...toString...方法略
}
1.1.4 步驟4:創(chuàng)建Dao接口
public interface AccountDao {
@Insert("insert into tbl_account(name,money)values(#{name},#{money})")
void save(Account account);
@Delete("delete from tbl_account where id = #{id} ")
void delete(Integer id);
@Update("update tbl_account set name = #{name} , money = #{money} where
id = #{id} ")
void update(Account account);
@Select("select * from tbl_account")
List<Account> findAll();
@Select("select * from tbl_account where id = #{id} ")
Account findById(Integer id);
}
1.1.5 步驟5:創(chuàng)建Service接口和實現(xiàn)類
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void save(Account account) {
accountDao.save(account);
}
public void update(Account account){
accountDao.update(account);
}
public void delete(Integer id) {
accountDao.delete(id);
}
public Account findById(Integer id) {
return accountDao.findById(id);
}
public List<Account> findAll() {
return accountDao.findAll();
}
}
1.1.6 步驟6:添加jdbc.properties文件
resources目錄下添加,用于配置數(shù)據(jù)庫連接四要素
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root
useSSL:關(guān)閉MySQL的SSL連接
1.1.7 步驟7:添加Mybatis核心配置文件
<?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>
<!--讀取外部properties配置文件-->
<properties resource="jdbc.properties"></properties>
<!--別名掃描的包路徑-->
<typeAliases>
<package name="com.itheima.domain"/>
</typeAliases>
<!--數(shù)據(jù)源-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}">
</property>
<property name="password" value="${jdbc.password}">
</property>
</dataSource>
</environment>
</environments>
<!--映射文件掃描包路徑-->
<mappers>
<package name="com.itheima.dao"></package>
</mappers>
</configuration>
1.1.8 步驟8:編寫應(yīng)用程序
public class App {
public static void main(String[] args) throws IOException {
// 1. 創(chuàng)建SqlSessionFactoryBuilder對象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new
SqlSessionFactoryBuilder();
// 2. 加載SqlMapConfig.xml配置文件
InputStream inputStream =
Resources.getResourceAsStream("SqlMapConfig.xml.bak");
// 3. 創(chuàng)建SqlSessionFactory對象
SqlSessionFactory sqlSessionFactory =
sqlSessionFactoryBuilder.build(inputStream);
// 4. 獲取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 5. 執(zhí)行SqlSession對象執(zhí)行查詢,獲取結(jié)果User
AccountDao accountDao = sqlSession.getMapper(AccountDao.class);
Account ac = accountDao.findById(1);
System.out.println(ac);
// 6. 釋放資源
sqlSession.close();
}
}
1.1.9 步驟9:運行程序
1.2 整合思路分析
Mybatis的基礎(chǔ)環(huán)境我們已經(jīng)準備好了,接下來就得分析下在上述的內(nèi)容中,哪些對象可以交給Spring來管理?
- Mybatis程序核心對象分析
從圖中可以獲取到,真正需要交給Spring管理的是SqlSessionFactory
- 整合Mybatis,就是將Mybatis用到的內(nèi)容交給Spring管理,分析下配置文件
說明:- 第一行讀取外部properties配置文件,Spring有提供具體的解決方案@PropertySource ,需要交給Spring
- 第二行起別名包掃描,為SqlSessionFactory服務(wù)的,需要交給Spring
第三行主要用于做連接池,Spring之前我們已經(jīng)整合了Druid連接池,這塊也需要交給Spring - 前面三行一起都是為了創(chuàng)建SqlSession對象用的,那么用Spring管理SqlSession對象嗎?回憶下SqlSession是由SqlSessionFactory創(chuàng)建出來的,所以只需要將SqlSessionFactory交給Spring管理即可。
- 第四行是Mapper接口和映射文件[如果使用注解就沒有該映射文件],這個是在獲取到SqlSession以后執(zhí)行具體操作的時候用,所以它和SqlSessionFactory創(chuàng)建的時機都不在同一個時間,可能需要單獨管理。
2 Spring整合Mybatis
前面我們已經(jīng)分析了Spring與Mybatis的整合,大體需要做兩件事,
第一件事是:Spring要管理MyBatis中的SqlSessionFactory
第二件事是:Spring要管理Mapper接口的掃描
具體該如何實現(xiàn),具體的步驟為:
2.1 步驟1:項目中導入整合需要的jar包
<dependency>
<!--Spring操作數(shù)據(jù)庫需要該jar包-->
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<!--
Spring與Mybatis整合的jar包
這個jar包mybatis在前面,是Mybatis提供的
-->
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
2.2 步驟2:創(chuàng)建Spring的主配置類
//配置類注解
@Configuration
//包掃描,主要掃描的是項目中的AccountServiceImpl類
@ComponentScan("com.itheima")
public class SpringConfig {
}
2.3 步驟3:創(chuàng)建數(shù)據(jù)源的配置類
在配置類中完成數(shù)據(jù)源的創(chuàng)建
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
return ds;
}
}
2.4 步驟4:主配置類中讀properties并引入數(shù)據(jù)源配置類
@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfig.class)
public class SpringConfig {
}
2.5 步驟5:創(chuàng)建Mybatis配置類并配置SqlSessionFactory
public class MybatisConfig {
//定義bean,SqlSessionFactoryBean,用于產(chǎn)生SqlSessionFactory對象
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//設(shè)置模型類的別名掃描
ssfb.setTypeAliasesPackage("com.itheima.domain");
//設(shè)置數(shù)據(jù)源
ssfb.setDataSource(dataSource);
return ssfb;
}
//定義bean,返回MapperScannerConfigurer對象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.itheima.dao");
return msc;
}
}
說明:
-
使用SqlSessionFactoryBean封裝SqlSessionFactory需要的環(huán)境信息
- SqlSessionFactoryBean是前面我們講解FactoryBean的一個子類,在該類中將SqlSessionFactory的創(chuàng)建進行了封裝,簡化對象的創(chuàng)建,我們只需要將其需要的內(nèi)容設(shè)置即可。
- 方法中有一個參數(shù)為dataSource,當前Spring容器中已經(jīng)創(chuàng)建了Druid數(shù)據(jù)源,類型剛好是DataSource類型,此時在初始化SqlSessionFactoryBean這個對象的時候,發(fā)現(xiàn)需要使用DataSource對象,而容器中剛好有這么一個對象,就自動加載了DruidDataSource對象。
-
使用MapperScannerConfigurer加載Dao接口,創(chuàng)建代理對象保存到IOC容器中
- 這個MapperScannerConfigurer對象也是MyBatis提供的專用于整合的jar包中的類,用來處理原始配置文件中的mappers相關(guān)配置,加載數(shù)據(jù)層的Mapper接口類
- MapperScannerConfigurer有一個核心屬性basePackage,就是用來設(shè)置所掃描的包路徑
2.6 步驟6:主配置類中引入Mybatis配置類
@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
2.7 步驟7:編寫運行類
在運行類中,從IOC容器中獲取Service對象,調(diào)用方法獲取結(jié)果文章來源:http://www.zghlxwxcb.cn/news/detail-767222.html
public class App2 {
public static void main(String[] args) {
ApplicationContext ctx = new
AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = ctx.getBean(AccountService.class);
Account ac = accountService.findById(1);
System.out.println(ac);
}
}
2.8 步驟8:運行程序
支持Spring與Mybatis的整合就已經(jīng)完成了,其中主要用到的兩個類分別是:文章來源地址http://www.zghlxwxcb.cn/news/detail-767222.html
- SqlSessionFactoryBean
- MapperScannerConfigurer
到了這里,關(guān)于【Spring教程12】Spring框架實戰(zhàn):Spring整合Mybatis全面深入詳解的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!