spring整合mybatis

前期表准备:

create table tbl_account(
    id int primary key auto_increment,
    name varchar(50) ,
    money int
);

insert into tbl_account values (1,'Tom',1000),(2,'Jerry',500);

一、没使用spring整合mybatis的时候,我们的mybatis写法如下所示:

程序测试:

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class App {
    public static void main(String[] args) throws IOException {
        // 1. 创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 2. 加载SqlMapConfig.xml配置文件
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 3. 创建SqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        // 4. 获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 5. 执行SqlSession对象执行查询,获取结果User
        AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

        Account ac = accountDao.findById(1);
        System.out.println(ac);

        // 6. 释放资源
        sqlSession.close();
    }
}

核心配置文件SqlMapConfig.xml:(以前我们的名字起的是官网形式:mybatis-config.xml)

新增知识点1:数据库的连接信息可以先写在jdbc.properties文件当中,然后通过 ${#} 符号来获取文件中的属性值

新增知识点2:当dao/mapper层的代理接口全是通过注解的形式来进行对数据库的增删改查等一些操作的时候,那么我们就可以不再写AccountDao.xml代理接口文件了(在核心配置文件中加载sql映射文件的地方直接加载dao层里的AccountDao类即可访问到该类了,以前我们都是加载到AccountDao.xml)




    
    
    
        
    
    
        
            
            

                
                
                
                
                
            
        
    
    

        
        
    

更正:起别名的那个地方是错误的,不是起别名的。

作用是:因为没有AccountDao代理开发接口的xml文件格式,所以这个 标签的意义是:加载sql映射文件到 AccountDao代理开发接口 通过sql语句查询出来的数据是通过该标签包下的Account类进行封装返回数据的

spring整合mybatis_第1张图片

dao/mapper层AccountDao:

package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

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 findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}

jdbc.properties:

spring整合mybatis_第2张图片

 运行结果如下所示:

spring整合mybatis_第3张图片

二、使用spring整合mybatis

其实也就是整合mybatis的核心配置文件(如下所示进行整合即可)

spring整合mybatis_第4张图片

 第一步导坐标:

spring整合mybatis_第5张图片

 第二步:既然我们使用spring整合mybatis了(整合的就是mybatis的核心配置文件)那么我们就可以把mybatis的核心配置文件给删除掉了:

spring整合mybatis_第6张图片

 代码演示如下所示:

App2程序测试类:

注意:获取IOC容器中被管理的bean的时候我们尽量写接口.class

 如:AccountService accountService =at.getBean(AccountService.class);

下面我们是用实现接口类的形式,原理是一样的,都是获取被管理的bean

package com.itheima;

import com.itheima.config.SpringConfig;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import com.itheima.service.impl.AccountServiceImpl;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App2 {

    public static void main(String[] args) {

        // 1、获取IOC容器    注意:这个IOC容器名称SpringConfig.class需要参考自己写的
        AnnotationConfigApplicationContext at =new AnnotationConfigApplicationContext(SpringConfig.class);

        // 2、获取IOC容器中被管理的bean
        AccountService accountService =at.getBean(AccountServiceImpl.class);

        // 3、调用bean的方法
        Account account =accountService.findById(2);
        System.out.println(account);
    }
}

java代码代替spring的xml配置文件:

SpringConfig:(导入 @Import({JdbcConfig.class,MybatisConfig.class})   )

package com.itheima.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;


/**
 *  第二种方式:纯注解开发方式
 *
 *      java代码代替spring的xml配置文件
 */

@Configuration  // 相当于spring xml配置文件中的总体标签    
@ComponentScan("com.itheima")   // 扫描该包下是否有注解bean的类,有的话就能取到该类对象了,也就是说有注解bean的类就会被IOC容器给管理了
@PropertySource({"jdbc.properties"})    // 配置加载jdbc.properties文件 使用$符获取数据
@Import({JdbcConfig.class,MybatisConfig.class})   
 // 导入这两个的目的就是相当于我们没有用spring整合mybatis的时候,mybatis测试程序中“加载核心置
//  文件”的步骤是一样的,这里导入后就说明加载了核心配置文件
public class SpringConfig {

}

 扫描到com.itheima包下的AccountServiceImpl类(该类加了bean注解):

eg1:那么说明该类就被IOC容器给管理起来了,我们只需要获取到IOC容器,然后拿到IOC容器内被管理的对象,就可以拿到该类

eg2:该业务逻辑层加上 private AccountDao accountDao; 就和代理接口accountDao产生依赖关系了,就可以调用代理接口中的如增删改查的方法了

package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service    // 注解 bean
public class AccountServiceImpl implements AccountService {

    @Autowired // 自动装配 处理依赖关系 private AccountDao accountDao = new AccountDao();
    /**
     *  也就是说:处理完依赖关系后,就相当于这里可以拿到代理接口AccountDao了,然后调用代理接口中的增删改查的方法即可
     */
    private AccountDao accountDao;

    public void save(Account account) {
        // 调用代理接口的save方法
        // 也就是说,当我们调用AccountService类当中的save()方法后,然后就调用了代理接口的save方法
        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 findAll() {
        return accountDao.findAll();
    }
}

业务逻辑层的AccountService接口(该接口写的代码和mapper代理接口其实是一样的):

eg:业务逻辑层就是做一些相应的逻辑,其实业务逻辑层的接口AccountService的代码和代理接口AccountDao的代码是一样的,只不过有时候会在实现业务层接口AccountServiceImpl的代码上加上了一些逻辑,

那么你可能会问:为什么业务逻辑层的接口和mapper接口代码一样的话,不直接让实现业务层接口的类直接实现mapper接口呢?

因为mapper接口有可能会写一些sql注解语句

package com.itheima.service;

import com.itheima.domain.Account;

import java.util.List;

public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List findAll();

    Account findById(Integer id);

}

代理接口AccountDao:

package com.itheima.dao;

import com.itheima.domain.Account;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

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 findAll();

    @Select("select * from tbl_account where id = #{id} ")
    Account findById(Integer id);
}

jdbcConfig:(做mybatis核心配置文件中的连接数据库的操作信息,这里把连接数据库的信息先写在jdbcConfig类当中,然后等会再通过引用类型传给MybatisConfig:专门处理mybatis核心配置文件的类当中

注意1:如果加载的是properties文件中的数据的话,就需要在SpringConfig类中添加注解@PropertySource({"jdbc.properties"}) // 配置加载jdbc.properties文件

package com.itheima.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

/**
 *  管理第三方jdbc的对象
 */
public class JdbcConfig {

    /**
     *  注解方式完成属性赋值
     *
     *      注意:这里注解的值是通过获取jdbc.properties文件中获取的,因此别忘记加@PropertySource("#")注解形式
     */

    @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/对象
     */


    @Bean
    public DataSource dataSource(){

        // 1、new 第三方bean/对象
        DruidDataSource dataSource =new DruidDataSource();

        // 2、给第三方bean/对象属性赋值
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        // 3、把第三方bean/对象返回给该方法
        return dataSource;
    }


}

MybatisConfig:

package com.itheima.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

/**
 *  spring整合mybatis ( 其实也就是整合mybatis的核心配置文件 )
 */

public class MybatisConfig {
   /*
     
    
            
    
    
        
            
            
                
                
                
                
                
            
        
    
    */

    /**
     *  该sqlSessionFactory方法new出来的SqlSessionFactoryBean对象相当于整合mybatis的核心配置文件中的上面那些信息
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){  // 传参的目的就是处理引用型依赖关系拿到DataSource对象
        // 1、new SqlSessionFactoryBean 对象
        SqlSessionFactoryBean sqfb =new SqlSessionFactoryBean();
        // 2、整合mybatis的核心配置信息
        sqfb.setTypeAliasesPackage("com.itheima.domain");
        sqfb.setDataSource(dataSource); // 引用型依赖关系为mybatis核心配置文件设置jdbc连接信息

        return sqfb;
    }

    /*

        
        
    
     */

/**
 *  该mapperScannerConfigurer方法new出来的MapperScannerConfigurer对象相当于整合mybatis的核心配置文件中的上面那些信息
 */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        // 1、new MapperScannerConfigurer对象
        MapperScannerConfigurer mp =new MapperScannerConfigurer();
        // 2、整合mybatis的核心配置信息
        mp.setBasePackage("com.itheima.dao");
// 因为这里我们是用代理接口注解形式做的处理数据库的,也就是说没有用UserMapper.xml形式,所以直
//接加载到dao层就行了,如果有xml核心配置文件的话,就加载到核心配置文件
        return mp;
    }
}

你可能感兴趣的:(笔记,mybatis,spring)