Spring整合Mybatis

问题导入

mybatis进行数据层操作的核心对象是谁?

1、MyBatis程序核心对象分析
图片[1]-Spring整合Mybatis-不念博客
2、 整合MyBatis
  • 使用SqlSessionFactoryBean封装SqlSessionFactory需要的环境信息
  • 使用MapperScannerConfigurer加载Dao接口,创建代理对象保存到IOC容器中

代码实现

问题导入

问题1:Spring整合mybatis的依赖叫什么?

问题2:Spring整合mybatis需要管理配置哪两个Bean,这两个Bean作用分别是什么?

【前置工作】
  1. 创建新的maven工程
  2. 在pom.xml中添加spring-context、druid、mybatis、mysql-connector-java等基础依赖。

<properties>
<!-- 定义spring的版本号 -->
<spring.version>5.2.10.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 导入阿里巴巴druid连接池(数据源) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<!-- 导入spring的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-jdbc包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 数据库mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
<!-- junit4 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!-- mybatis的包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<!-- mybatis整合spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
<properties>
    <!-- 定义spring的版本号 -->
    <spring.version>5.2.10.RELEASE</spring.version>
</properties>

<dependencies>

    <!-- 导入阿里巴巴druid连接池(数据源) -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.23</version>
    </dependency>

    <!-- 导入spring的包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    <!-- spring-jdbc包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- 数据库mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.22</version>
        <scope>runtime</scope>
    </dependency>

    <!-- junit4 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13</version>
        <scope>test</scope>
    </dependency>

    <!-- mybatis的包 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.0</version>
    </dependency>

    <!-- mybatis整合spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.4</version>
    </dependency>

    <!-- lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.10</version>
    </dependency>
</dependencies>
<properties> <!-- 定义spring的版本号 --> <spring.version>5.2.10.RELEASE</spring.version> </properties> <dependencies> <!-- 导入阿里巴巴druid连接池(数据源) --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.23</version> </dependency> <!-- 导入spring的包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!-- spring-jdbc包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- 数据库mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.22</version> <scope>runtime</scope> </dependency> <!-- junit4 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> <scope>test</scope> </dependency> <!-- mybatis的包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.0</version> </dependency> <!-- mybatis整合spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.4</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> </dependencies>
  1. 准备service和dao层基础代码
@Data
public class Account {
private Integer id; //主键
private String name; //用户名
private Double money; //金额
}
@Data
public class Account {

    private Integer id;  //主键
    private String name;  //用户名
    private Double money;  //金额
}
@Data public class Account { private Integer id; //主键 private String name; //用户名 private Double money; //金额 }
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);
}
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);
}
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); }
/**
* 业务接口
*/
public interface AccountService {
void save(Account account);
void delete(Integer id);
void update(Account account);
List<Account> findAll();
Account findById(Integer id);
}
/**
 * 业务接口
 */
public interface AccountService {

    void save(Account account);

    void delete(Integer id);

    void update(Account account);

    List<Account> findAll();

    Account findById(Integer id);

}
/** * 业务接口 */ 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();
}
}
@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();
    }
}
@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(); } }

开始整合

【第一步】导入Spring整合Mybatis依赖

上面的pom.xml文件中已经导入

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!--mybatis整合spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>
<!--mybatis整合spring-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.10.RELEASE</version> </dependency> <!--mybatis整合spring--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
【第二步】创建JdbcConfig配置DataSource数据源
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_db 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;
}
}
/**
 * 数据库配置类
 */
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;
    }
}
/** * 数据库配置类 */ 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; } }
【第三步】创建MybatisConfig整合mybatis

注:MapperScannerConfigurer不能与@Value放在同一个配置类中,否则会导致@Value失效,因为MapperScannerConfigurer会比PropertySource先加载

解决方法:如果要放在同一个类中,可以在mapperScannerConfigurer()方法前添加static关键字。

public class MybatisConfig {
//定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//指定实体类的基包,定义别名
factoryBean.setTypeAliasesPackage("com.itheima.domain");
//配置数据源
factoryBean.setDataSource(dataSource);
return factoryBean;
}
//定义bean,返回MapperScannerConfigurer对象
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
//配置dao接口所在的包
mapperScanner.setBasePackage("com.itheima.dao");
return mapperScanner;
}
}
public class MybatisConfig {
    
    //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //指定实体类的基包,定义别名
        factoryBean.setTypeAliasesPackage("com.itheima.domain");
        //配置数据源
        factoryBean.setDataSource(dataSource);
        return factoryBean;
    }
    
    //定义bean,返回MapperScannerConfigurer对象
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
        //配置dao接口所在的包
        mapperScanner.setBasePackage("com.itheima.dao");
        return mapperScanner;
    }
}
public class MybatisConfig { //定义bean,SqlSessionFactoryBean,用于产生SqlSessionFactory对象 @Bean public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){ SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); //指定实体类的基包,定义别名 factoryBean.setTypeAliasesPackage("com.itheima.domain"); //配置数据源 factoryBean.setDataSource(dataSource); return factoryBean; } //定义bean,返回MapperScannerConfigurer对象 @Bean public MapperScannerConfigurer mapperScannerConfigurer(){ MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer(); //配置dao接口所在的包 mapperScanner.setBasePackage("com.itheima.dao"); return mapperScanner; } }
【第四步】创建SpringConfig主配置类进行包扫描和加载其他配置类
@Configuration //这是一个配置类
@ComponentScan("com.demo.service") //扫描com.demo.service下面的所有类
@PropertySource("classpath:jdbc.properties") //加载属性文件
@Import({JdbcConfig.class,MybatisConfig.class}) //导入其它配置文件
public class SpringConfig {
}
@Configuration  //这是一个配置类
@ComponentScan("com.demo.service")  //扫描com.demo.service下面的所有类
@PropertySource("classpath:jdbc.properties")  //加载属性文件
@Import({JdbcConfig.class,MybatisConfig.class})  //导入其它配置文件
public class SpringConfig {
}
@Configuration //这是一个配置类 @ComponentScan("com.demo.service") //扫描com.demo.service下面的所有类 @PropertySource("classpath:jdbc.properties") //加载属性文件 @Import({JdbcConfig.class,MybatisConfig.class}) //导入其它配置文件 public class SpringConfig { }
【第五步】定义测试类进行测试
public class AppTest {
@Test
public void testFindById() {
//加载主配置类
ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
//获取业务对象
AccountService accountService = ctx.getBean(AccountService.class);
//调用业务方法
Account account = accountService.findById(2);
//输出结果
System.out.println(account);
}
}
public class AppTest {

    @Test
    public void testFindById() {
        //加载主配置类
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        //获取业务对象
        AccountService accountService = ctx.getBean(AccountService.class);
        //调用业务方法
        Account account = accountService.findById(2);
        //输出结果
        System.out.println(account);
    }
}
public class AppTest { @Test public void testFindById() { //加载主配置类 ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); //获取业务对象 AccountService accountService = ctx.getBean(AccountService.class); //调用业务方法 Account account = accountService.findById(2); //输出结果 System.out.println(account); } }

运行结果

图片[2]-Spring整合Mybatis-不念博客
© 版权声明
THE END