Spring整合mybatis

1 Spring整合mybatis【重點(diǎn)】

1.1 思路分析

問題導(dǎo)入

mybatis進(jìn)行數(shù)據(jù)層操作的核心對(duì)象是誰?

1.1.1 MyBatis程序核心對(duì)象分析
image-20210730114303147.png
1.1.2 整合MyBatis
  • 使用SqlSessionFactoryBean封裝SqlSessionFactory需要的環(huán)境信息
image-20210730114342060.png
  • 使用MapperScannerConfigurer加載Dao接口,創(chuàng)建代理對(duì)象保存到IOC容器中
![image-20200831155517797.png](https://upload-images.jianshu.io/upload_images/17212199-eaea23296c166e48.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

1.2 代碼實(shí)現(xiàn)

問題導(dǎo)入

問題1:Spring整合mybatis的依賴叫什么?

問題2:Spring整合mybatis需要管理配置哪兩個(gè)Bean,這兩個(gè)Bean作用分別是什么?

【前置工作】
  1. 在pom.xml中添加spring-context、druid、mybatis、mysql-connector-java等基礎(chǔ)依賴。
  2. 準(zhǔn)備service和dao層基礎(chǔ)代碼
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();
    }
}
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);
}
【第一步】導(dǎo)入Spring整合Mybatis依賴
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>
【第二步】創(chuàng)建JdbcConfig配置DataSource數(shù)據(jù)源
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=root
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;
    }
}
【第三步】創(chuàng)建MybatisConfig整合mybatis
public class MybatisConfig {
    //定義bean,SqlSessionFactoryBean,用于產(chǎn)生SqlSessionFactory對(duì)象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        ssfb.setTypeAliasesPackage("com.itheima.domain");
        ssfb.setDataSource(dataSource);
        return ssfb;
    }
    //定義bean,返回MapperScannerConfigurer對(duì)象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}
【第四步】創(chuàng)建SpringConfig主配置類進(jìn)行包掃描和加載其他配置類
@Configuration
@ComponentScan("com.itheima")
//@PropertySource:加載類路徑j(luò)dbc.properties文件
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}
【第五步】定義測(cè)試類進(jìn)行測(cè)試
public class App {
    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 Spring整合Junit單元測(cè)試【重點(diǎn)】

問題導(dǎo)入

Spring整合Junit的兩個(gè)注解作用分別是什么?

【第一步】導(dǎo)入整合的依賴坐標(biāo)spring-test

<!--junit-->
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>5.1.9.RELEASE</version>
</dependency>

【第二步】使用Spring整合Junit專用的類加載器

【第三步】加載配置文件或者配置類

//【第二步】使用Spring整合Junit專用的類加載器
@RunWith(SpringJUnit4ClassRunner.class)
//【第三步】加載配置文件或者配置類
@ContextConfiguration(classes = {SpringConfiguration.class}) //加載配置類
//@ContextConfiguration(locations={"classpath:applicationContext.xml"})//加載配置文件
public class AccountServiceTest {
    //支持自動(dòng)裝配注入bean
    @Autowired
    private AccountService accountService;

    @Test
    public void testFindById(){
        System.out.println(accountService.findById(1));
    }

    @Test
    public void testFindAll(){
        System.out.println(accountService.findAll());
    }
}

==注意:junit的依賴至少要是4.12版本,可以是4.13等版本,否則出現(xiàn)如下異常:==

image-20200831155517797.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容