前言
為了鞏固所學(xué)的知識,作者嘗試著開始發(fā)布一些學(xué)習(xí)筆記類的博客,方便日后回顧。當(dāng)然,如果能幫到一些萌新進行新技術(shù)的學(xué)習(xí)那也是極好的。作者菜菜一枚,文章中如果有記錄錯誤,歡迎讀者朋友們批評指正。
(博客的參考源碼可以在我主頁的資源里找到,如果在學(xué)習(xí)的過程中有什么疑問歡迎大家在評論區(qū)向我提出)
發(fā)現(xiàn)寶藏
前些天發(fā)現(xiàn)了一個巨牛的人工智能學(xué)習(xí)網(wǎng)站,通俗易懂,風(fēng)趣幽默,忍不住分享一下給大家?!緦毑厝肟凇?。
一、Mybatis一般開發(fā)流程
1. 設(shè)計創(chuàng)建數(shù)據(jù)庫表tbl_account
- 建表查詢語句示例
create database spring_db;
use spring_db;
drop table if exists tbl_account;
create table tbl_account(
id int primary key auto_increment,
name varchar(20),
account varchar(20)
);
INSERT INTO tbl_account VALUES (1, 'Tom', 1000);
INSERT INTO tbl_account VALUES (2, 'Jerry', 500);
- 效果
2. 創(chuàng)建對應(yīng)maven模塊并在pom.xml導(dǎo)入對應(yīng)坐標(biāo)
<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>
3. 創(chuàng)建對應(yīng)實體類Account
public class Account implements Serializable {
//此處省略getter、setter和toString方法
private Integer id;
private String name;
private Double money;
}
4. 創(chuàng)建mybatis核心配置文件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>
<properties resource="jdbc.properties"></properties>
<typeAliases>
<package name="com.itheima.domain"/>
</typeAliases>
<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="org.example.dao"></package>
</mappers>
</configuration>
5. 創(chuàng)建數(shù)據(jù)庫表信息jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root
6. 用注解的方式創(chuàng)建編寫mappper代理接口AccountDao(或者是一個接口對應(yīng)一個mapper文件)
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);
}
7. 創(chuàng)建模擬測試類APP
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("mybatis-config.xml");
// 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();
}
}
- 模擬測試類運行結(jié)果
9. 文件結(jié)構(gòu)參考
二、spring整合mybatis思路分析
1. 我們知道spring的特點之一就是能管理bean,那mybatis中有哪些bean是需要交給spring去管理的呢?我們可以將mybatis的示例運行程序APP分為以下幾個部分,通過觀察我們可以發(fā)現(xiàn)主要有如下幾個對象:SqlSessionFactory、SqlSession、AccountDao
- 雖然AccountDao是直接執(zhí)行業(yè)務(wù)的,但是它不是根源上的對象,而且隨著業(yè)務(wù)需求不同,造出來的對象也不一樣,所以它不是最核心的對象。
- SqlSession對象是由工廠造出來的,類似于連接池,該對象實際已經(jīng)造好
- 所以最核心的對象是SqlSessionFactory
2. 通過觀察Mybatis的核心配置文件我們可以將其分為如下幾個部分:
- 第一部分 的作用是配置加載數(shù)據(jù)庫信息,有沒有的區(qū)別是加載的信息是否在本配置文件獲取,與SqlSessionFactory沒什么關(guān)系
- 第二部分 的作用是配置Mybatis操作完后得到的數(shù)據(jù)是什么類型,是SqlSessionFactory對象中可選的一個屬性
- 第三部分 dataSourcre 標(biāo)簽中的部分是數(shù)據(jù)庫連接信息,是必須的,如果沒有該內(nèi)容,SqlSessionFactory無法獲知操作的數(shù)據(jù)庫信息
- 第三部分 transactionManager 標(biāo)簽中的部分是事務(wù)處理相關(guān)內(nèi)容,與SqlSessionFactory也有關(guān)系,本博客暫時不做探討
- 第四部分 是業(yè)務(wù)操作相關(guān)的,即使沒有,SqlSessionFactory也能創(chuàng)建。但是在實際開發(fā)中,如果需要用到Mapper代理開發(fā),就需要配置這部分內(nèi)容。
3. 小結(jié)
綜上考慮,spring要重點管理的mybatis中的核心對象是 SqlSessionFactory,用Spring創(chuàng)建出SqlSessionFactory對象和業(yè)務(wù)相關(guān)的 Mapper映射對象是我們的主要目標(biāo)。
三、Spring整合Mybatis環(huán)境準(zhǔn)備(注解開發(fā))
- 在pom.xml文件中導(dǎo)入spring開發(fā)相關(guān)坐標(biāo)
<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>
<!--spring操作數(shù)據(jù)庫-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
2. 創(chuàng)建Spring核心配置類SpringConfig
@Configuration
@ComponentScan("org.example")
public class SpringConfig {
}
3. 創(chuàng)建業(yè)務(wù)接口AccountService
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
4. 創(chuàng)建對應(yīng)的實現(xiàn)類AccountServiceImpl
@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();
}
}
5. 數(shù)據(jù)庫連接信息
- 創(chuàng)建數(shù)據(jù)庫信息配置類JdbcConfig
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;
}
}
- 加載數(shù)據(jù)庫信息properties文件
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
public class SpringConfig {
}
- 加載數(shù)據(jù)庫信息配置類
方式一:在核心配置類上加@Configuration,通過Spring核心配置類SpringConfig中的@ComponentScan注解掃描
方式二:手工導(dǎo)入
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfig.class)
public class SpringConfig {
}
6. 文件結(jié)構(gòu)預(yù)覽
四、Spring整合Mybatis
1. MybatisConfig配置類
- 創(chuàng)建Mybatis配置類MybatisConfig(實現(xiàn)目標(biāo):創(chuàng)建SqlSessionFactoryBean)
public class MybatisConfig {
//定義bean,SqlSessionFactoryBean,用于產(chǎn)生SqlSessionFactory對象
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//設(shè)置別名
ssfb.setTypeAliasesPackage("org.example.domain");
//配置數(shù)據(jù)源
ssfb.setDataSource(dataSource);
return ssfb;
}
//定義bean,返回MapperScannerConfigurer對象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("org.example.dao");
return msc;
}
}
- 加載Mybatis配置類
@Configuration
@ComponentScan("org.example")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
2. 創(chuàng)建模擬測試類
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);
}
}
3. 運行結(jié)果
4. 文件結(jié)構(gòu)預(yù)覽
五、小結(jié)
簡單來說,Spring整合Mybatis就是在Spring開發(fā)的基礎(chǔ)上多了一個MyBatisConfig配置文件
文章來源:http://www.zghlxwxcb.cn/news/detail-471562.html
總結(jié)
歡迎各位留言交流以及批評指正,如果文章對您有幫助或者覺得作者寫的還不錯可以點一下關(guān)注,點贊,收藏支持一下。
(博客的參考源碼可以在我主頁的資源里找到,如果在學(xué)習(xí)的過程中有什么疑問歡迎大家在評論區(qū)向我提出)文章來源地址http://www.zghlxwxcb.cn/news/detail-471562.html
到了這里,關(guān)于Spring 整合 Mybatis -- Spring快速入門保姆級教程(四)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!