一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - SpringBoot集成mybatis實例

SpringBoot集成mybatis實例

2020-09-13 14:41xixicat Java教程

本篇文章主要介紹了SpringBoot集成mybatis實例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一、使用mybatis-spring-boot-starter

1、添加依賴

?
1
2
3
4
5
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>1.0.0</version>
</dependency>

2、啟動時導入指定的sql(application.properties)

?
1
spring.datasource.schema=import.sql

3、annotation形式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@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

?
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <typeAliases>
    <package name="sample.mybatis.domain"/>
  </typeAliases>
  <mappers>
    <mapper resource="sample/mybatis/mapper/CityMapper.xml"/>
  </mappers>
</configuration>

application.properties

?
1
2
spring.datasource.schema=import.sql
mybatis.config=mybatis-config.xml

mapper

?
1
2
3
4
5
6
7
8
9
10
11
@Component
public class CityMapper {
 
  @Autowired
  private SqlSessionTemplate sqlSessionTemplate;
 
  public City selectCityById(long id) {
    return this.sqlSessionTemplate.selectOne("selectCityById", id);
  }
 
}

二、手工集成

1、annotation方式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@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方式

數據源

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
 
  <context:property-placeholder ignore-unresolvable="true" />
 
  <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="poolName" value="springHikariCP" />
    <property name="connectionTestQuery" value="SELECT 1" />
    <property name="dataSourceClassName" value="${database.dataSourceClassName}" />
    <property name="maximumPoolSize" value="${pool.maxPoolSize}" />
    <property name="idleTimeout" value="${pool.idleTimeout}" />
 
    <property name="dataSourceProperties">
      <props>
        <prop key="url">${database.url}</prop>
        <prop key="user">${database.username}</prop>
        <prop key="password">${database.password}</prop>
      </props>
    </property>
  </bean>
 
  <!-- HikariCP configuration -->
  <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
  </bean>
 
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!-- 配置mybatis配置文件的位置 -->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="typeAliasesPackage" value="com.xixicat.domain"/>
    <!-- 配置掃描Mapper XML的位置 -->
    <property name="mapperLocations" value="classpath:com/xixicat/modules/dao/*.xml"/>
 
 
  </bean>
 
  <!-- 配置掃描Mapper接口的包路徑 -->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <property name="basePackage" value="com.xixicat.repository.mapper"/>
  </bean>
 
  <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="sqlSessionFactory"/>
  </bean>
 
  <bean id="transactionManager"
     class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
     p:dataSource-ref="dataSource"/>
  <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />
 
  <tx:advice id="txAdvice" transaction-manager="transactionManager" >
    <tx:attributes>
      <tx:method name="start*" propagation="REQUIRED"/>
      <tx:method name="submit*" propagation="REQUIRED"/>
      <tx:method name="clear*" propagation="REQUIRED"/>
      <tx:method name="create*" propagation="REQUIRED"/>
      <tx:method name="activate*" propagation="REQUIRED"/>
      <tx:method name="save*" propagation="REQUIRED"/>
      <tx:method name="insert*" propagation="REQUIRED"/>
      <tx:method name="add*" propagation="REQUIRED"/>
      <tx:method name="update*" propagation="REQUIRED"/>
      <tx:method name="delete*" propagation="REQUIRED"/>
      <tx:method name="remove*" propagation="REQUIRED"/>
      <tx:method name="execute*" propagation="REQUIRED"/>
      <tx:method name="del*" propagation="REQUIRED"/>
      <tx:method name="*" read-only="true"/>
    </tx:attributes>
  </tx:advice>
  <aop:config proxy-target-class="true" expose-proxy="true">
    <aop:pointcut id="pt" expression="execution(public * com.xixicat.service.*.*(..))" />
    <aop:advisor order="200" pointcut-ref="pt" advice-ref="txAdvice"/>
  </aop:config>
</beans>

aop依賴

?
1
2
3
4
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

mybatis-spring等依賴

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!-- boot dependency mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
      <scope>compile</scope>
    </dependency>
 
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
 
    <!--<dependency>-->
      <!--<groupId>org.hsqldb</groupId>-->
      <!--<artifactId>hsqldb</artifactId>-->
      <!--<scope>runtime</scope>-->
    <!--</dependency>-->
 
    <dependency>
      <groupId>com.zaxxer</groupId>
      <artifactId>HikariCP-java6</artifactId>
      <version>2.3.8</version>
    </dependency>

指定xml配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@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);
  }
 
}

點評

跟傳統的方式集成最為直接,而且事務配置也比較容易上手

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://segmentfault.com/a/1190000004275305

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色ccc36| 91桃色污 | 成人网视频免费播放 | 草草线在成年免费视频网站 | 四虎成人永久地址 | chinses台湾男同志hd | 武侠艳妇屈辱的张开双腿 | 兽操人 | 女海盗斯蒂内塔的复仇2免费观看 | 国产盗摄wc厕所撒尿视频 | 国产成人精品视频午夜 | 国产成人综合亚洲亚洲欧美 | 污斗罗大陆| 亚洲欧美日韩中文字幕网址 | 好湿好紧太硬了我太爽了网站 | 日产一区二区 | 亚洲社区在线观看 | 波多野结在线 | 500福利第一巨人导航 | 韩国一大片a毛片女同 | 午夜影院免费观看视频 | 视频免费| 91久久青青青国产免费 | 日本孕妇与黑人xxxxxx | 男女乱淫真视频播放网站 | mm131亚洲 | 亚洲另类中文字幕 | 欧美日韩视频在线一区二区 | 日本三级欧美三级人妇英文 | 美国玩尿眼道videos | 国产精品久久久精品日日 | 91视频一区 | 国产视频一区 | 久久久久久久久a免费 | 日本一区二区视频免费播放 | 大陆日韩欧美 | 欧美日韩视频在线第一区二区三区 | 欧美亚洲国产成人不卡 | 韩国最新三级网站在线播放 | 久久精品国产视频澳门 | 成年看片免费高清观看 |