• Spring基础——Spring配置Mybatis连接数据库


    数据库类型:MySQL
    数据库版本:8.0.36
    请务必让导入的mysql包与数据库版本兼容
    源码仓库:java_spring_learn_repo/tree/master/spring_mybatis
    jdbc配置文件需自行添加,下文有模板样例

    Spring配置MyBatis流程

    1. 添加Mybatis依赖

    
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.2version>
    dependency>
    
    <dependency>
      <groupId>com.mysqlgroupId>
      <artifactId>mysql-connector-jartifactId>
      <version>8.1.0version>
    dependency>
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.10version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.6version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    2. 配置MySQL数据库连接池

    2.1 首先创建jdbc配置文件

    • jdbc.properties
    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://xxxxxxx
    jdbc.username=xxxxx
    jdbc.password=xxxxx
    
    • 1
    • 2
    • 3
    • 4

    2.2 配置数据库DataSource

    • 使用注解@PropertySource将配置文件导入配置类中
    @PropertySource("classpath:jdbc.properties")
    
    • 1
    • 这里使用的数据库连接池是阿里的Druid
    @PropertySource("classpath:jdbc.properties")
    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;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    3. 配置MyBatis

    3.1 配置SqlSessionFactoryBean

    • 每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。
    • 但在Spring中SqlSessionFactory是封装到Bean中的,Spring已经将前面步骤给准备好了,我们只需要直接创建SqlSessionFactoryBean就行
    @Bean
    public SqlSessionFactoryBean createSqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 配置类型别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.nobugnolife.entity");
        // 传入druid的datasource
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    3.2 配置mybatis Mapper Bean

    • 因为Dao层是全部交由Mybatis实现访问接口的,因此Spring无法直接配置Mybatis内部bean,所以这里还需配置Mybatis的Mapper映射路径
    @Bean
    public MapperScannerConfigurer maperConfigurer(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.nobugnolife.dao");
        return mapperScannerConfigurer;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4. 创建MyBatis Mapper接口

    • 定义执行数据库访问操作的接口
    public interface UserDao {
    
        @Select("select id,name,money from tb_user where id=#{id}")
        User findUserById(Integer id);
    
        @Update("update tb_user set money=#{money} where id=#{id}")
        Integer updateMoneyById(@Param("id")Integer id,@Param("money") Double money);
    
        @Select("select id,name,money from tb_user")
        List<User> findAll();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6. 测试数据输出

    • Service
    @Override
    public User buySomeThing(Integer id, Double productValue) {
        User user = userDao.findUserById(id);
        user.setMoney(user.getMoney()-productValue);
        Integer msg = userDao.updateMoneyById(id,user.getMoney());
        // 不做任何边界检测,直接返回数据
        return user;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • test
    @Test
    public void testBuySomeThing(){
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = ctx.getBean(UserService.class);
        Double productValue = 25.00;
        User user = userService.buySomeThing(1,productValue);
        System.out.println("用户:"+user.getName()+"在某xx平台消费了"+productValue+"\t当前余额:"+user.getMoney());
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    test

  • 相关阅读:
    附录1-爬虫的一些技巧
    功能:crypto-js加密解密
    Remix+Cloudflare Pages+D1 快速上手
    区块链2024
    自动驾驶算法岗笔试题 | 一道有意思的数学题 | 解析及代码实现
    第十四届蓝桥杯省赛C/C++大学B组真题-飞机降落
    计算机网络-物理层
    thinkphp5 注入 反序列化写文件 phar反序列化
    力扣(LeetCode)260. 只出现一次的数字 III(C++)
    Elasticsearch:使用 function_score 中的weight和gauss衰减函数定制搜索结果的分数
  • 原文地址:https://blog.csdn.net/day_to_die/article/details/136540093