Spring(整合 MyBatis)

Spring 整合 MyBatis

1 目标:

  • 使用spring整合MyBatis

2 分析

  • 搭建环境:mybatis、spring、整合jar
    • 项目名:day10_sm
  • 整合过程中,将采用配置类的方法。
  • 步骤:
    • 编写UserMapper 接口,继承通用mapper
    • 编写UserService接口,查询所有
    • 编写UserServiceImpl实现类,查询所有
    • 编写Spring配置类
    • 编写MyBatis配置类,取代 SqlConfigMap.xml文件
    • 测试类

3 实现

3.1 编写UserMapper 接口,继承通用mapper

package com.czxy.sm.mapper;

import com.czxy.sm.domain.User;
import tk.mybatis.mapper.common.Mapper;


public interface UserMapper extends Mapper<User> {
}

3.2 编写UserService接口,查询所有

package com.czxy.sm.service;

import com.czxy.sm.domain.User;

import java.util.List;

public interface UserService {
    /**
     * 查询所有
     * @return
     */
    public List<User> selectAll();
}

3.3 编写UserServiceImpl实现类,查询所有

  • service实现类需要添加到spring容器,需要使用 @Service注解
package com.czxy.sm.service.impl;

import com.czxy.sm.domain.User;
import com.czxy.sm.mapper.UserMapper;
import com.czxy.sm.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }
}

3.4 编写Spring配置类

  • 在spring配置类中,主要配置数据源 DataSource (连接池)
  • 注意:配置类负责所有组件扫描
package com.czxy.sm.config;

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

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:db.properties")
@ComponentScan(basePackages = "com.czxy.sm")
public class SpringConfiguration {

    @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 druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);

        return druidDataSource;
    }


}

  • db.properties

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm_db1
    jdbc.username=root
    jdbc.password=1234
    

3.5 编写MyBatis配置类,取代 SqlConfigMap.xml文件

  • 配置 SQLSessionFactory 用于取代 SqlMapConfig.xml 文件(别名、插件 等)
  • Mapper扫描器需要单独配置
    • MyBatis内置:org.mybatis.spring.mapper.MapperScannerConfigurer
    • 通用Mapper:tk.mybatis.spring.mapper.MapperScannerConfigurer
package com.czxy.sm.config;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.Properties;


public class MyBatisConfiguration {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        //1 创建工厂
        // 1.通过工厂bean创建对象,最后需要调用 getObject()获得具体的对象
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        //2 设置数据-- SqlMapConfig.xml 配置信息

        // 1.1 设置数据源
        factoryBean.setDataSource(dataSource);
        // 1.2 设置别名包扫描
        factoryBean.setTypeAliasesPackage("com.czxy.sm.domain");
        // 1.3 全局配置:驼峰映射
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(config);

        // 2 插件配置
        // 2.1 分页插件
        PageHelper pageHelper = new PageHelper();
        Properties pageProps = new Properties();
        pageProps.setProperty("dialect", "mysql");
        pageProps.setProperty("rowBoundsWithCount", "true");
        pageHelper.setProperties(pageProps);
        factoryBean.setPlugins(new Interceptor[] { pageHelper });


        // 返回SqlSessionFactory
        return factoryBean.getObject();
    }

    /**
     * 扫描Dao的包,查找各种XxxMapper接口,创建好UserMapper等对象存入到IOC的容器中
     * @return
     */
    @Bean
    public MapperScannerConfigurer mapperScanner() {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();

        
        configurer.setBasePackage("com.czxy.sm.mapper");
        return configurer;
    }

}

3.6 测试类

package com.czxy.sm;

import com.czxy.sm.config.MyBatisConfiguration;
import com.czxy.sm.config.SpringConfiguration;
import com.czxy.sm.domain.User;
import com.czxy.sm.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;


@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class, MyBatisConfiguration.class})
public class TestSM {

    @Resource
    private UserService userService;

    @Test
    public void testDemo() {
        List<User> list = userService.selectAll();
        list.forEach(System.out::println);
    }
}

你可能感兴趣的:(spring,spring,boot,java)