Spring整合MyBatis

文章详细介绍了如何在Spring环境中整合MyBatis,包括导入依赖、创建实体类、Dao接口、Service接口及实现类,配置jdbc.properties和Mybatis核心配置文件,最后通过Spring管理SqlSessionFactory和Mapper接口,实现数据库操作。
摘要由CSDN通过智能技术生成

Spring整合MyBatis思路分析


环境准备

创建项目导入jar包

<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>

根据表创建实体类

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double money;
	//setter...getter...toString...方法略    
}

创建Dao接口

public interface AccountDao {

    @Insert("insert into tb_account(name,money)values(#{name},#{money})")
    void save(Account account);

    @Delete("delete from tb_account where id = #{id} ")
    void delete(Integer id);

    @Update("update tb_account set name = #{name} , money = #{money} where id = #{id} ")
    void update(Account account);

    @Select("select * from tb_account")
    List<Account> findAll();

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

创建Service接口和是实现类

@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();
    }
}

添加jdbc.properties文件

resources目录下添加,用于配置数据库连接四要素

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?useSSL=false
jdbc.username=root
jdbc.password=123456

useSSL:关闭MySQL的SSL连接

添加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.mzh.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="com.mzh.dao"></package>
    </mappers>
</configuration>

编写应用程序

 //创建SqlSessionFactoryBuilder对象
 SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
 //加载MyBatis.xml配置文件
 InputStream inputStream =  Resources.getResourceAsStream("MyBatis.xml");
 //创建SqlSessionFactory对象
 SqlSessionFactory sessionFactory = sqlSessionFactoryBuilder.build(inputStream);
 //获取SqlSession对象
 SqlSession sqlSession = sessionFactory.openSession();
 //执行SqlSession对象执行查询,获取结果
 AccountDao accountDao = sqlSession.getMapper(AccountDao.class);

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

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

运行程序

在这里插入图片描述

整合思路分析

Mybatis的基础环境我们已经准备好了,接下来就得分析下在上述的内容中,哪些对象可以交给Spring来管理?

  • Mybatis程序核心对象分析
    在这里插入图片描述
    从图中可以获取到,真正需要交给Spring管理的是SqlSessionFactory
  • 整合Mybatis,就是将Mybatis用到的内容交给Spring管理,分析下配置文件

在这里插入图片描述
说明

  • 第一行读取外部properties配置文件,Spring有提供具体的解决方案@PropertySource,需要交给Spring
  • 第二行起别名包扫描,为SqlSessionFactory服务的,需要交给Spring
  • 第三行主要用于做连接池,Spring之前我们已经整合了Druid连接池,这块也需要交给Spring
  • 前面三行一起都是为了创建SqlSession对象用的,SqlSession是由SqlSessionFactory创建出来的,所以只需要将SqlSessionFactory交给Spring管理即可
  • 第四行是Mapper接口和映射文件[如果使用注解就没有该映射文件],这个是在获取到SqlSession以后执行具体操作的时候用,所以它和SqlSessionFactory创建的时机都不在同一个时间,可能需要单独管理

Spring整合MyBatis

前面我们已经分析了Spring与Mybatis的整合,大体需要做两件事

第一件事是:Spring要管理MyBatis中的SqlSessionFactory

第二件事是:Spring要管理Mapper接口的扫描
具体的步骤为:

项目中导入整合需要的jar包

<dependency>
    <!--Spring操作数据库需要该jar包-->
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>
<dependency>
    <!--
		SpringMybatis整合的jar包
		这个jar包mybatis在前面,是Mybatis提供的
	-->
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>

创建Spring的主配置类

//配置类注解
@Configuration
//包扫描,主要扫描的是项目中的AccountServiceImpl类
@ComponentScan("com.itheima")
public class SpringConfig {
}

创建数据源的配置类

在配置类中完成数据源的创建

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;
    }
}

主配置类中读properties并引入数据源配置类

@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfig.class)
public class SpringConfig {
}

创建Mybatis配置类并配置SqlSessionFactory

public class MyBatisConfig {
    //定义bean,SqlSessionFactoryBean用于生产SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
        //设置模型类的别名扫描
        ssfb.setTypeAliasesPackage("com.mzh.domain");
        //设置数据源
        ssfb.setDataSource(dataSource);
        return ssfb;
    }

    //定义Bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.mzh.dao");
        return msc;
    }
}

说明:

  • 使用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息
    在这里插入图片描述

    • SqlSessionFactoryBean是FactoryBean的一个子类,在该类中将SqlSessionFactory的创建进行了封装,简化对象的创建,我们只需要将其需要的内容设置即可。
    • 方法中有一个参数为dataSource,当前Spring容器中已经创建了Druid数据源,类型刚好是DataSource类型,此时在初始化SqlSessionFactoryBean这个对象的时候,发现需要使用DataSource对象,而容器中刚好有这么一个对象,就自动加载了DruidDataSource对象。
  • 使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中
    在这里插入图片描述

    • 这个MapperScannerConfigurer对象也是MyBatis提供的专用于整合的jar包中的类,用来处理原始配置文件中的mappers相关配置,加载数据层的Mapper接口类
    • MapperScannerConfigurer有一个核心属性basePackage,就是用来设置所扫描的包路径

主配置类中引入Mybatis配置类

@Configuration
@ComponentScan("com.itheima")
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MybatisConfig.class})
public class SpringConfig {
}

编写运行类

在运行类中,从IOC容器中获取Service对象,调用方法获取结果

public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

        AccountService service = applicationContext.getBean(AccountService.class);

        Account account = service.findById(2);

        System.out.println(account);
   }

运行程序

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值