Spring利用注解整合Mybatis的方法詳解
一、環(huán)境準(zhǔn)備
步驟1:數(shù)據(jù)庫(kù)相關(guān)
建庫(kù)建表
創(chuàng)建spring_db數(shù)據(jù)庫(kù),tb_user表
create database spring_db character set utf8;
use spring_db;
create table tb_user(
id int primary key auto_increment,
name varchar(35),
age int
);
插入數(shù)據(jù)
添加幾條實(shí)驗(yàn)數(shù)據(jù)
INSERT INTO spring_db.tb_user (name, age) VALUES ('bighorn', 18);
INSERT INTO spring_db.tb_user (name, age) VALUES ('大角牛', 20);
INSERT INTO spring_db.tb_user (name, age) VALUES ('倔強(qiáng)的牛角', 100);
步驟2:導(dǎo)入jar包
創(chuàng)建Maven工程,在pom.xml文件導(dǎo)入相關(guān)依賴
<dependencies>
<dependency>
<!--springframework框架-->
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--JDK9 以后需要導(dǎo)的注解依賴-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--Mybatis依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--Druid連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--mysql 驅(qū)動(dòng)-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
<scope>runtime</scope>
</dependency>
</dependencies>
步驟3:創(chuàng)建模型類
根據(jù)tb_user表字段,創(chuàng)建User模型類
public class User {
private Integer id;
private String name;
private Integer age;
//省略setter和getter方法
}
步驟4:創(chuàng)建Dao接口和實(shí)現(xiàn)類
創(chuàng)建簡(jiǎn)單的UserDao接口和UserDaoImpl實(shí)現(xiàn)類,里面就一個(gè)查詢方法。
/*UserDao接口*/
public interface UserDao {
@Select("select * from tb_user where id = #{id} ")
User findById(Integer id);
}
/*UserDaoImpl實(shí)現(xiàn)類*/
@Repository
public class UserDaoImpl implements UserDao {
@Override
public User findById(Integer id) {
return null;
}
}
步驟5:創(chuàng)建Service接口和實(shí)現(xiàn)類
創(chuàng)建簡(jiǎn)單的UserService接口和UserServiceImpl實(shí)現(xiàn)類
/*UserService接口*/
public interface UserService {
void findById(Integer id);
}
/*UserServiceImpl實(shí)現(xiàn)類*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void findById(Integer id) {
User user = userDao.findById(id);
System.out.println("id為" + id + "的用戶姓名:" + user.getName());
System.out.println("id為" + id + "的用戶年齡:" + user.getAge());
}
}
步驟6:添加jdbc.properties文件
resources目錄下添加jdbc.properties文件,用于配置數(shù)據(jù)庫(kù)連接四要素
# 注冊(cè)驅(qū)動(dòng),可以缺省,會(huì)根據(jù)url自動(dòng)識(shí)別 jdbc.driver=com.mysql.cj.jdbc.Driver # 數(shù)據(jù)庫(kù)連接地址 jdbc.url=jdbc:mysql://localhost:3306/spring_db # 數(shù)據(jù)庫(kù)管理員名稱 jdbc.username=root # 數(shù)據(jù)庫(kù)密碼 jdbc.password=123456
步驟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"/>
<!--別名掃描的包路徑-->
<typeAliases>
<package name="com.bighorn.pojo"/>
</typeAliases>
<!--配置數(shù)據(jù)源-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--映射文件掃描包路徑-->
<mappers>
<package name="com.bighorn.dao"/>
</mappers>
</configuration>
步驟8:編寫測(cè)試程序
public static void main(String[] args) throws IOException {
//1.加載mybatis的核心配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//2.獲取 SqlSessionFactory對(duì)象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3. 獲取SqlSession對(duì)象,用它來(lái)執(zhí)行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//4.獲取userMapper接口的代理對(duì)象
UserDao userDao = sqlSession.getMapper(UserDao.class);
//5.執(zhí)行查詢,獲取結(jié)果User
User user = userDao.findById(1);
System.out.println(user);
//6. 釋放資源
sqlSession.close();
}
運(yùn)行結(jié)果截圖
說(shuō)明環(huán)境配置沒有問(wèn)題

二、整合思路分析

以上流程可以全部移交給Spring來(lái)處理
其中有兩個(gè)重要的整合:
- Spring要管理MyBatis中的SqlSessionFactory
- Spring要管理Mapper接口的掃描
注解整合 MyBatis 的開發(fā)步驟:
- 修改 mybatis 外部配置文件格式為注解格式;
- 業(yè)務(wù)類使用 @Component 或其衍生注解聲明 bean,使用 @Autowired 注入對(duì)象;
- 建立配置文件 DataSourceConfig與 MyBatisConfig 類,并將其導(dǎo)入到核心配置類 SpringConfig;
- 開啟注解掃描;
- 使用 AnnotationConfigApplicationContext 對(duì)象加載配置項(xiàng)。
三、整合步驟
步驟1:導(dǎo)入整合jar包
mybatis-spring是Mybatis提供的Spring與Mybatis整合的jar包
<dependency>
<!--Spring操作數(shù)據(jù)庫(kù)需要該jar包-->
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<!--
Mybatis提供的Spring與Mybatis整合的jar包
-->
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
步驟2:創(chuàng)建數(shù)據(jù)源配置類
創(chuàng)建DataSourceConfig類,完成Druid數(shù)據(jù)源的創(chuàng)建
/*數(shù)據(jù)源配置類*/
// 加載jdbc.properties配置文件
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
//用SpEl表達(dá)式將屬性注入
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
// 將方法的返回值放置Spring容器中
@Bean("druidDataSource")
public DruidDataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
步驟3:創(chuàng)建Mybatis配置類
主要是讓Spring管理兩個(gè)第三方Bean:SqlSessionFactoryBean、MapperScannerConfigurer
說(shuō)明:
SqlSessionFactoryBean是FactoryBean的一個(gè)子類,也是mybatis-spring整合jar包中的類,該類將SqlSessionFactory的創(chuàng)建進(jìn)行了封裝,簡(jiǎn)化對(duì)象的創(chuàng)建,
MapperScannerConfigurer也是MyBatis提供的整合jar包中的類,用來(lái)處理原始mapper映射文件相關(guān)配置,加載數(shù)據(jù)層的Mapper(Dao)接口類。核心屬性basePackage,就是用來(lái)設(shè)置所掃描的包路徑
/*Mybatis配置類*/
public class MybatisConfig {
//定義bean:SqlSessionFactoryBean,用于產(chǎn)生SqlSessionFactory對(duì)象
@Bean
public SqlSessionFactoryBean sqlSessionFactory(@Autowired DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//設(shè)置模型類的別名掃描
ssfb.setTypeAliasesPackage("com.bighorn.pojo");
//設(shè)置數(shù)據(jù)源
ssfb.setDataSource(dataSource);
return ssfb;
}
//定義bean,返回MapperScannerConfigurer對(duì)象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.bighorn.dao");
return msc;
}
}
步驟4:創(chuàng)建Spring主配置類
創(chuàng)建SpringConfig類,開啟注解掃描、引入外部配置類(數(shù)據(jù)源配置類和Mybatis配置類)
/*Spring核心配置類*/
//配置類注解
@Configuration
//開啟注解掃描功能
@ComponentScan("com.bighorn")
//引入數(shù)據(jù)源配置類和Mybatis配置類
@Import({DataSourceConfig.class,MybatisConfig.class})
public class SpringConfig {
}
步驟5:編寫運(yùn)行程序
在運(yùn)行類中,從IoC容器中獲取UserService對(duì)象,調(diào)用其方法
public static void main(String[] args) throws SQLException {
//獲取配置類初始化容器
ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
//從容器中獲取UserService對(duì)象
UserService userService = context.getBean(UserService.class);
//調(diào)用service的方法
userService.findById(3);
}
運(yùn)行結(jié)果如下
說(shuō)明Spring整合Mybatis成功辣!

以上就是Spring利用注解整合Mybatis的方法詳解的詳細(xì)內(nèi)容,更多關(guān)于Spring注解整合Mybatis的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
maven報(bào)錯(cuò):Failed to execute goal on p
這篇文章主要介紹了maven報(bào)錯(cuò):Failed to execute goal on project問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
Java輸出通過(guò)InetAddress獲得的IP地址數(shù)組詳細(xì)解析
由于byte被認(rèn)為是unsigned byte,所以最高位的1將會(huì)被解釋為符號(hào)位,另外Java中存儲(chǔ)是按照補(bǔ)碼存儲(chǔ),所以1000 0111會(huì)被認(rèn)為是補(bǔ)碼形式,轉(zhuǎn)換成原碼便是1111 0001,轉(zhuǎn)換成十進(jìn)制數(shù)便是-1212013-09-09
java實(shí)現(xiàn)簡(jiǎn)單音樂(lè)播放器
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡(jiǎn)單音樂(lè)播放器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-06-06
SpringBoot設(shè)置靜態(tài)資源訪問(wèn)控制和封裝集成方案
這篇文章主要介紹了SpringBoot靜態(tài)資源訪問(wèn)控制和封裝集成方案,關(guān)于springboot靜態(tài)資源訪問(wèn)的問(wèn)題,小編是通過(guò)自定義webconfig實(shí)現(xiàn)WebMvcConfigurer,重寫addResourceHandlers方法,具體完整代碼跟隨小編一起看看吧2021-08-08
IntelliJ IDEA2023中運(yùn)行Spring Boot找不到VM options進(jìn)
這篇文章主要介紹了IntelliJ IDEA2023中運(yùn)行Spring Boot找不到VM options進(jìn)行端口的修改的問(wèn)題解決,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11
springBoot項(xiàng)目打包idea的多種方法
這篇文章主要介紹了springBoot項(xiàng)目打包idea的多種方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
Feign Client 超時(shí)時(shí)間配置不生效的解決
這篇文章主要介紹了Feign Client 超時(shí)時(shí)間配置不生效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09

