目录
一、纯MyBatis独立开发程序。
(1)数据库与数据表。
(2)实体类。
(3)dao层接口。(Mapper代理模式、无SQL映射文件——注解配置映射关系)
(4)MyBatis核心配置文件。
(5)应用测试程序。(类App)
二、Spring整合MyBatis的思路分析。(Spring管理哪个bean?)
(1)MyBatis运行程序分析。
<1>初始化SqlSessionFactory。
<2>获取连接(SqlSession)。获取xxxMapper接口。
<3>调用数据层方法完成操作。
<4>关闭连接。
(2)MyBatis核心配置文件分析。
<1>初始属性、加载外部资源文件。
<2>初始化类型别名。
<3>配置数据源连接信息。
<4>初始化映射配置。
(3)分析小结。
三、Spring整合MyBatis。(实操)
(1)导入Spring整合Mybatis核心依赖坐标。
<1>spring-context。(基础核心)
<2>druid。(阿里数据源)
<3>mybatis。(基础核心)
<4>mysql-connector-java。(mysql核心jar)
<5>spring-jdbc。(spring操作数据库核心jar)
<6>mybatis-spring。(spring整合mybatis核心jar)
<7>lombok。(快速开发)
(2)service层。
<1>AccountService接口。
<2>AccountServiceImpl实现类。
(3)dao层。(Mapper代理模式开发)
(4)Jdbc配置类。(配置数据源信息)
(5)MyBatis配置类。(取代MyBatis核心配置文件)
<1>SqlSessionFactoryBean、MapperScannerConfigurer对象。
(6)Spring配置类。
(7)测试程序。(类App02)
一、纯MyBatis独立开发程序。
(1)数据库与数据表。
- 数据库:hyl。数据表:tb_account。
(2)实体类。
- pom文件引入Lombok依赖。(帮助快速开发:无需手动提供getter、setter方法、构造器、toString()方法等...)
<!--Lombok依赖坐标--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> <scope>provided</scope> </dependency>
- 在包(domain)下创建对应数据库字段的实体类用于封装。
- 实体类上使用注解@Data使Lombok生效。
package com.hyl.domain; import lombok.Data; @Data public class Account { private Integer id; private String name; private Double money; }
(3)dao层接口。(Mapper代理模式、无SQL映射文件——注解配置映射关系)
- 只有接口无实现类。使用Mapper代理模式这一套开发模式。
- 无SQL映射文件。使用注解形式(@Select、@Insert、@Delete、@Update)配置其映射关系并完成SQL语句的书写。
package com.hyl.dao; import com.hyl.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 tb_account (name,money) values (#{name},#{money})") void save(Account account); /** * 根据id删除 */ @Delete("delete from tb_account where id = #{id}") void delete(Integer id); /** * 更新 * @param account */ @Update("update tb_account set name = #{name} , money = #{money} where id = #{id}") void update(Account account); /** * 查询所有 * @return */ @Select("select * from tb_account ") List<Account> selectAll(); /** * 根据id查询 * @param id * @return */ @Select("select * from tb_account where id = #{id}") Account selectById(Integer id); }
(4)MyBatis核心配置文件。
- pom文件引入mybatis核心依赖与Java连接数据库核心依赖。
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency>
- <properties>加载外部properties配置文件。
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/hyl jdbc.username=root jdbc.password=root123
- 加载JDBC连接MySQL的数据源连接信息。
- <mappers>中的<package>注册指定包下的所有mapper接口。
<?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="db.properties"></properties> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <typeAliases> <package name="com.hyl.domain"/> </typeAliases> <environments default="development"> <environment id="development"> <!--配置JDBC事务管理--> <transactionManager type="JDBC"></transactionManager> <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.hyl.dao"/> </mappers> </configuration>
(5)应用测试程序。(类App)
- 获得SqlSessionFactory对象。
- 获得SqlSession对象。
- 通过SqlSession对象调用getMapper("执行业务的接口.class")获取真正执行业务操作的xxxMapper接口。
- 通过调用对应的方法执行查询操作即可。
- 最后释放SqlSession对象资源。
package com.hyl; import com.hyl.dao.AccountDao; import com.hyl.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(); //加载mybatis主配置文件 InputStream resourceAsStream = Resources.getResourceAsStream("mybatisConfig.xml"); //3.创建SqlSessionFactory对象 SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream); //4.创建SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //5.执行SqlSession对象的getMapper方法获取执行业务的接口Mapper AccountDao accountDao = sqlSession.getMapper(AccountDao.class); Account account = accountDao.selectById(1); System.out.println("查询结果:"+account); //6.释放SqlSession资源 sqlSession.close(); } }
- 测试类App程序运行结果如下。
二、Spring整合MyBatis的思路分析。(Spring管理哪个bean?)
(1)MyBatis运行程序分析。
- 从上面的纯MyBatis开发项目的运行程序(App)分析。并将其拆分为几个重要的模块。
- 因为Spring是用来管理bean的,那么需要确定有哪些bean是需要交给Spring管理的!
<1>初始化SqlSessionFactory。
- 核心对象SqlSessionFactory。(需要交给spring管理)
<2>获取连接(SqlSession)。获取xxxMapper接口。
- 无核心需要被spring管理的对象。
- SqlSession对象是由SqlSessionFactory初始化那个阶段就已经造好。
<3>调用数据层方法完成操作。
- 无核心需要被spring管理的对象。
- 虽然accountDao是执行业务的对象,但依旧不是根源的对象。并且随着业务的更换,造出的对象也会更新。
<4>关闭连接。
- 无核心需要被spring管理的对象。
(2)MyBatis核心配置文件分析。
- MyBatis核心配置文件所有的配置都是围绕着SqlSessionFactory对象进行的。
<1>初始属性、加载外部资源文件。
- 读取外部文件的值。不是核心关键所在。
<2>初始化类型别名。
- 操作数据库得到的数据结果进行封装到对应的实体类中。次要核心。
<3>配置数据源连接信息。
- 配置数据源对象DataSource。核心所在。
- 造出SqlSession对象是操作对应的数据库的。而这些配置都是为核心对象SqlSessionFactory服务的。
<4>初始化映射配置。
- 这部分主要关于业务的操作。
- 初始化SqlSessionFactory对象后,再根据不同的配置、不同的接口,获得不同的xxxMapper,再去操作不同的库与表。所以也不是核心关键所在。
(3)分析小结。
- 最终经过分析:MyBatis核心的对象SqlSessionFactory是需要交给Spring进行管理的。
三、Spring整合MyBatis。(实操)
- 注:数据库、数据表、实体类的代码与纯MyBatis开发程序一致。
(1)导入Spring整合Mybatis核心依赖坐标。
<1>spring-context。(基础核心)
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.18</version> </dependency>
<2>druid。(阿里数据源)
<!--阿里数据库连接池druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.8</version> </dependency>
<3>mybatis。(基础核心)
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency>
<4>mysql-connector-java。(mysql核心jar)
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency>
<5>spring-jdbc。(spring操作数据库核心jar)
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.18</version> </dependency>
<6>mybatis-spring。(spring整合mybatis核心jar)
- 注意这个jar与mybatis的基础依赖的版本是有联系的。随着版本的更替都会更替。
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency>
<7>lombok。(快速开发)
<!--Lombok依赖坐标--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> <scope>provided</scope> </dependency>
(2)service层。
<1>AccountService接口。
package com.hyl.service; import com.hyl.domain.Account; import java.util.List; public interface AccountService { /** * 新增 * @param account */ void save(Account account); /** * 更新 * @param account */ void update(Account account); /** * 删除 * @param id */ void delete(Integer id); /** * 根据id查询 * @param id * @return */ Account selectById(Integer id); /** * 查询所有 * @return */ List<Account> selectAll(); }
<2>AccountServiceImpl实现类。
- 使用注解@Service将该实现类交给spring容器管理。
- 使用注解@Autowired完成dao层AccountDao的自动装配。
package com.hyl.service.impl; import com.hyl.dao.AccountDao; import com.hyl.domain.Account; import com.hyl.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountDao accountDao; @Override public void save(Account account) { accountDao.save(account); } @Override public void update(Account account) { accountDao.update(account); } @Override public void delete(Integer id) { accountDao.delete(id); } @Override public Account selectById(Integer id) { return accountDao.selectById(id); } @Override public List<Account> selectAll() { return accountDao.selectAll(); } }
(3)dao层。(Mapper代理模式开发)
- AccountDao接口。
- 无SQL映射文件。(使用注解@Selcet、@Insert、@Delete、@Update配置映射关系与SQL语句)
package com.hyl.dao; import com.hyl.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 tb_account (name,money) values (#{name},#{money})") void save(Account account); /** * 根据id删除 */ @Delete("delete from tb_account where id = #{id}") void delete(Integer id); /** * 更新 * @param account */ @Update("update tb_account set name = #{name} , money = #{money} where id = #{id}") void update(Account account); /** * 查询所有 * @return */ @Select("select * from tb_account ") List<Account> selectAll(); /** * 根据id查询 * @param id * @return */ @Select("select * from tb_account where id = #{id}") Account selectById(Integer id); }
(4)Jdbc配置类。(配置数据源信息)
- 使用注解@Bean标明返回数据源对象的方法。这样Spring会自动将DataSource对象交给Spring容器管理。其它的组件(bean)都可以使用。
package com.hyl.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; 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; /** * 1、定义方法,返回需要管理的bean(这里使用阿里提供的第三方数据源druid) * 2、使用注解@Bean 将方法的返回值声明为一个Spring管理的Bean。 * 这意味着Spring会调用这个方法,并将方法的返回值(bean)存储到Spring容器中,供其他组件使用。 */ @Bean public DataSource dataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName(driver); druidDataSource.setUrl(url); druidDataSource.setUsername(userName); druidDataSource.setPassword(password); return druidDataSource; } }
(5)MyBatis配置类。(取代MyBatis核心配置文件)
- 使用注解@Bean标明返回SqlSessionFactory对象的方法。这样Spring会自动将SqlSessionFactory对象交给Spring容器管理。其它的组件(bean)都可以使用。
- 因为根据上方分析:SqlSessionFactory对象的初始化都与MyBatis核心配置文件有关,所以在返回SqlSessionFactory的方法里面要设置很多东西!
<1>SqlSessionFactoryBean、MapperScannerConfigurer对象。
- 为了简化开发,spring整合mybatis中提供了类SqlSessionFactoryBean制造bean。
- 最终的Mybatis配置类的代码如下。
package com.hyl.config; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.context.annotation.Bean; import javax.sql.DataSource; public class MyBatisConfig { @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean(); //代替Mybatis核心配置文件标签<typeAliases> ssfb.setTypeAliasesPackage("com.hyl.domain"); //因为Jdbc配置类的方法使用了@Bean注解生产DataSource对象的方法。 // 则可以使用形参注入DataSource。再通过方法设置使DataSource ssfb.setDataSource(dataSource); //jdbc事务管理默认有spring-jdbc依赖处理 return ssfb; } //单独方法代替Mybatis核心配置文件标签<Mappers> //使用spring整合mybatis提供的类MapperScannerConfigurer完成映射文件的扫描 @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); //设置映射在哪些包下 mapperScannerConfigurer.setBasePackage("com.hyl.dao"); return mapperScannerConfigurer; } }
- 加后缀.bak——>注释原来的MyBatis核心配置文件。方便测试。
(6)Spring配置类。
- 为了快速的开发——所以选择纯注解的开发模式。而放弃使用XML配置文件开发模式。
- 使用注解@Configuration标明这是spring的一个配置类。(平替spring配置文件)
- 使用注解@ComponentScan扫描指定包下类的注解。
- 使用注解@PropertySource加载外部properties配置文件。
- 使用注解@Import引入其它的配置类(JdbcConfig、MyBatisConfig配置类)。
package com.hyl.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; @Configuration @ComponentScan("com.hyl") @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class,MyBatisConfig.class}) public class SpringConfig { }
(7)测试程序。(类App02)
- 通过类AnnotationConfigApplicationContext加载spring配置类。
- spring配置类再通过注解完成其它配置类的扫描、包的注解扫描。
- 配和注解@Service使用,用容器对象调用getBean()方法获取AccountServiceImpl对象。
- 最后调用操作数据库的方法。(这里以测试根据id查询演示)。
package com.hyl; import com.hyl.config.SpringConfig; import com.hyl.domain.Account; import com.hyl.service.AccountService; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class App02 { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class); AccountService accountService = applicationContext.getBean(AccountService.class); Account account = accountService.selectById(2); System.out.println(account); applicationContext.close(); } }
- 测试类App02程序运行结果如下。
- 到这里就是就实现了Spring整合MyBatis的全部操作了!也是完成快速开发的重要一步。