mybatis如何带你飞

119 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第6天,点击查看活动详情

mybatis配置

  • 上面的pom设置已经准备了mybatis开发阶段的基本jar。 有了上述的包就可以搭建mybatis . 正常我们在我们的springboot项目中配置一个bean配置的类 MybatisConfig

设置数据源

@Bean
@ConfigurationProperties("spring.datasource")
public DataSource primaryDataSource() {
    // 这里为了演示,暂时写死 。 实际上是可以通过autoConfigure装配参数的
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setUsername("root");
    dataSource.setPassword("123456");
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://192.168.44.130:3306/others?useUnicode=true&characterEncoding=utf8");
    return dataSource;
}
​

设置开启事务

  • 优秀的架构没有事务是能使用的。我们配置事务也是很简单的。在springboot中我们推荐使用java代码来配置事务的。下面的配置我们为了容易阅读。配置在TransactionConfig类中
@Bean
public DataSourceTransactionManager primaryTransactionManager() {
    return new DataSourceTransactionManager(dataSource);
}
​
  • 首先是配置事务管理器。事务管理的是数据源。所以这里我们需要将MybatisConfig中的DataSource加载进来。这里不多说

  • 在springboot中我们只需要在方法上添加Bean注解,就相当于我们在spring的xml中配置的bean标签。在java代码中我们可以进行我们业务处理。个人理解感觉更加的可控。 因为我们使用的mysql。所以这里我们简单的使用druid的数据源

设置扫描

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setSqlSessionFactory(primarySqlSessionFactory());
    //每张表对应的*.java,interface类型的Java文件
    mapperScannerConfigurer.setBasePackage("com.github.zxhtom.**.mapper");
    return mapperScannerConfigurer;
}
​

设置sqlsessionfactory

​
@Bean
public SqlSessionFactory primarySqlSessionFactory() {
    SqlSessionFactory factory = null;
    try {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(primaryDataSource());
        sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/com/github/zxhtom.**./*.xml"));
        factory = sqlSessionFactoryBean.getObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return factory;
}
​
  • 在mybatis中sqlsesson是我们操作数据库最直接的java类。管理sqlsession就是上面的sqlsessionFactory 。 所以我们配置它也是必须的。因为和spring整合。Mybatis的SqlsessionFactory交由给spring的SqlsessionfactoryBean管理。所以我们先构建SqlSessionFactoryBean。然后配置必须的数据源、Configuration、mybatis的xml路径等等信息
  • SqlSessionFactoryBean 设置出了spring的FactoryBean属性意外。最重要的是可以设置Mybatis的sqlsessionfactory的属性。上面我们只是简单的设置了。后期可以根据架构的需求进行不断的完善。
  • 可以设置插件、缓存、别名、映射处理器、事务、环境等等所有mybatis的配置
  • springboot 中我们的mapper接口也是交由spring来扫描的。之前mybatis程序我们是一个一个手动加入的。spring的特性可以直接扫描指定路径的所有java类。这里我们就设置了一下mapper的路径。