网站建设资讯

NEWS

网站建设资讯

使用SpringBoot如何实现集成mybatis

使用SpringBoot如何实现集成mybatis?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

创新互联建站专注于南丰网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供南丰营销型网站建设,南丰网站制作、南丰网页设计、南丰网站官网定制、重庆小程序开发服务,打造南丰网络公司原创品牌,更为您提供南丰网站排名全网营销落地服务。

一、使用mybatis-spring-boot-starter

1、添加依赖


  org.mybatis.spring.boot
  mybatis-spring-boot-starter
  1.0.0

2、启动时导入指定的sql(application.properties)

spring.datasource.schema=import.sql

3、annotation形式

@SpringBootApplication
@MapperScan("sample.mybatis.mapper")
public class SampleMybatisApplication implements CommandLineRunner {

  @Autowired
  private CityMapper cityMapper;

  public static void main(String[] args) {
    SpringApplication.run(SampleMybatisApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println(this.cityMapper.findByState("CA"));
  }

}

4、xml方式

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>


  
    
  
  
    
  

application.properties

spring.datasource.schema=import.sql
mybatis.config=mybatis-config.xml

mapper

@Component
public class CityMapper {

  @Autowired
  private SqlSessionTemplate sqlSessionTemplate;

  public City selectCityById(long id) {
    return this.sqlSessionTemplate.selectOne("selectCityById", id);
  }

}

二、手工集成

1、annotation方式

@Configuration
@MapperScan("com.xixicat.modules.dao")
@PropertySources({ @PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = true), @PropertySource(value = "file:./application.properties", ignoreResourceNotFound = true) })
public class MybatisConfig {
  
  @Value("${name:}")
  private String name;

  @Value("${database.driverClassName}")
  private String driverClass;

  @Value("${database.url}")
  private String jdbcUrl;

  @Value("${database.username}")
  private String dbUser;

  @Value("${database.password}")
  private String dbPwd;

  @Value("${pool.minPoolSize}")
  private int minPoolSize;

  @Value("${pool.maxPoolSize}")
  private int maxPoolSize;


  @Bean
  public Filter characterEncodingFilter() {
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    characterEncodingFilter.setForceEncoding(true);
    return characterEncodingFilter;
  }

  @Bean(destroyMethod = "close")
  public DataSource dataSource(){
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName(driverClass);
    hikariConfig.setJdbcUrl(jdbcUrl);
    hikariConfig.setUsername(dbUser);
    hikariConfig.setPassword(dbPwd);
    hikariConfig.setPoolName("springHikariCP");
    hikariConfig.setAutoCommit(false);
    hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");
     
    hikariConfig.setMinimumIdle(minPoolSize);
    hikariConfig.setMaximumPoolSize(maxPoolSize);
    hikariConfig.setConnectionInitSql("SELECT 1");
    
    HikariDataSource dataSource = new HikariDataSource(hikariConfig);
    return dataSource;
  }
  
  @Bean
  public PlatformTransactionManager transactionManager() {
    return new DataSourceTransactionManager(dataSource());
  }

  @Bean
  public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setFailFast(true);
    sessionFactory.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
    return sessionFactory.getObject();
  }
}

点评

这种方式有点别扭,而且配置不了拦截式事务拦截,只能采用注解声明,有些冗余

2、xml方式

数据源

<?xml version="1.0" encoding="UTF-8" ?>


  

  
    
    
    
    
    

    
      
        ${database.url}
        ${database.username}
        ${database.password}
      
    
  

  
  
    
  

  
    
    
    
    
    
    


  

  
  
    
    
  

  
    
  

  
  

  
    
      
      
      
      
      
      
      
      
      
      
      
      
      
      
    
  
  
    
    
  

aop依赖

    
      org.springframework.boot
      spring-boot-starter-aop
    

mybatis-spring等依赖


    
      org.mybatis
      mybatis
      3.3.0
      compile
    
    
      org.mybatis
      mybatis-spring
      1.2.2
      compile
    

    
      MySQL
      mysql-connector-java
      5.1.6
    

    
      
      
      
    

    
      com.zaxxer
      HikariCP-java6
      2.3.8
    

指定xml配置文件

@Configuration
@ComponentScan( basePackages = {"com.xixicat"} )
@ImportResource("classpath:applicationContext-mybatis.xml")
@EnableAutoConfiguration
public class AppMain {

  // 用于处理编码问题
  @Bean
  public Filter characterEncodingFilter() {
    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    characterEncodingFilter.setForceEncoding(true);
    return characterEncodingFilter;
  }

  //文件下载
  @Bean
  public HttpMessageConverters restFileDownloadSupport() {
    ByteArrayHttpMessageConverter arrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    return new HttpMessageConverters(arrayHttpMessageConverter);
  }

  public static void main(String[] args) throws Exception {
    SpringApplication.run(AppMain.class, args);
  }

}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注创新互联行业资讯频道,感谢您对创新互联的支持。


分享名称:使用SpringBoot如何实现集成mybatis
文章位置:http://njwzjz.com/article/psecgo.html