【Spring】整合第三方框架 之 MyBatis

新博客:https://blog.bigdataboy.cn/article/450.html

MyBatis 说明

mybatis-spring官网:https://mybatis.org/spring/zh/index.html

介绍:MyBatis-Spring 会帮助你将
MyBatis 代码无缝地整合Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapperSqlSession注入bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException

添加 Jar 依赖

pom.xml 文件添加,注意 版本问题

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.10.RELEASE</version>
    </dependency>
    <!--  spring jdbc 操作  -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.2</version>
    </dependency>
    <!--  阿里巴巴数据源  -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.24</version>
    </dependency>
    <!--  mybatis  -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.6</version>
    </dependency>
    <!--  mybatis spring 结合 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.8</version>
    </dependency>
</dependencies>

添加 配置类 和 配置文件

数据库 Sql 文件

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `users` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL,
  `money` double(255, 0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Compact;

-- ----------------------------
-- Records of account
-- ----------------------------
INSERT INTO `account` VALUES (1, 'a', 100);
INSERT INTO `account` VALUES (2, 'b', 200);

SET FOREIGN_KEY_CHECKS = 1;

jdbc.properties

resources 文件夹下

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root

JdbcConfig 配置类

Spring 第三方 Bean 管理

@Configuration
public class JdbcConfig {

    @Value("${jdbc.driver}")
    public String driverClassName;

    @Value("${jdbc.url}")
    public String url;

    @Value("${jdbc.username}")
    public String username;

    @Value("${jdbc.password}")
    public String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

MyBatisConfig 配置类

Spring 第三方 Bean 管理

@Configuration
public class MyBatisConfig {

    @Bean  // 连接工厂 Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        return factoryBean;
    }

    @Bean  // Mapper Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("cn.bigdataboy.dao"); // 设置 Mapper 映射的包,扫描 Mapper 注解,已经转化成 Mapper, 相对于以前的 Mapper 配置
        return mapperScannerConfigurer;
    }
}

Spring 配置类

@Configuration
@ComponentScan({"cn.bigdataboy"})
@PropertySource({"classpath:jdbc.properties"})
@Import({MyBatisConfig.class, JdbcConfig.class}) // 导入配置
public class SpringConfig {
}

添加 实体类

实体类,就是查询结果的映射类,在 domain文件夹下

public class Account {
    private int id;
    private String users;
    private Double money;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", users='" + users + '\'' +
                ", money=" + money +
                '}';
    }
}

添加 dao 层

dao 层是数据处理,结合 Mybatis 后,就是 原来的 Mapper 配置

@Mapper
public interface AccountDao {
    @Select("SELECT * FROM account WHERE id = #{userId}")
    Account getUserById(@Param("userId") int userId);

    @Select("SELECT * FROM account")
    List<Account> getAllUser();
}

添加 service 层

业务处理层,实现两个功能,按 id 查询查询全部

@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public Account getUserById(int id) {
        return accountDao.getUserById(id);
    }

    @Override
    public List<Account> getAllUser() {
        return accountDao.getAllUser();
    }
}

测试

public class App {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        AccountService accountService = context.getBean(AccountService.class);
        Account account = accountService.getUserById(1);
        System.out.println(account);
        System.out.println(accountService.getAllUser());
    }
}

mark

案例代码:https://pan.bigdataboy.cn/s/mXnux

发表评论 / Comment

用心评论~