spring boot integrated mybatis three ways!--转
https://github.com/spring-projects/spring-boot/issues/5400
一、使用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
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方式
数据源
<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>
aop依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
mybatis-spring等依赖
<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配置文件
@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);
}
}
点评
跟传统的方式集成最为直接,而且事务配置也比较容易上手
spring boot integrated mybatis three ways!--转的更多相关文章
- Spring Boot 整合 Mybatis 实现 Druid 多数据源详解
摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “清醒时做事,糊涂时跑步,大怒时睡觉,独处时思考” 本文提纲一.多数据源的应用场景二.运行 sp ...
- 使用intelliJ创建 spring boot + gradle + mybatis站点
Spring boot作为快速入门是不错的选择,现在似乎没有看到大家写过spring boot + gradle + mybatis在intellij下的入门文章,碰巧.Net同事问到,我想我也可以写 ...
- Spring Boot整合Mybatis并完成CRUD操作
MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作. 为什么要使用Mybatis?我们需要掌握Mybatis吗? 说的官 ...
- Spring boot整合Mybatis
时隔两个月的再来写博客的感觉怎么样呢,只能用“棒”来形容了.闲话少说,直接入正题,之前的博客中有说过,将spring与mybatis整个后开发会更爽,基于现在springboot已经成为整个业界开发主 ...
- Spring boot教程mybatis访问MySQL的尝试
Windows 10家庭中文版,Eclipse,Java 1.8,spring boot 2.1.0,mybatis-spring-boot-starter 1.3.2,com.github.page ...
- spring boot 实现mybatis拦截器
spring boot 实现mybatis拦截器 项目是个报表系统,服务端是简单的Java web架构,直接在请求参数里面加了个query id参数,就是mybatis mapper的query id ...
- spring boot 整合 mybatis 以及原理
同上一篇文章一样,spring boot 整合 mybatis过程中没有看见SqlSessionFactory,sqlsession(sqlsessionTemplate),就连在spring框架整合 ...
- Spring Boot集成MyBatis开发Web项目
1.Maven构建Spring Boot 创建Maven Web工程,引入spring-boot-starter-parent依赖 <project xmlns="http://mav ...
- 详解Spring Boot集成MyBatis的开发流程
MyBatis是支持定制化SQL.存储过程以及高级映射的优秀的持久层框架,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集. spring Boot是能支持快速创建Spring应用的Java框 ...
随机推荐
- 8.QList QMap QVariant
QList int main1(int argc, char *argv[]) { QApplication a(argc, argv); QList<,,}; mylist << ...
- 算法入门经典第六章 例题6-14 Abbott的复仇(Abbott's Revenge)BFS算法实现
Sample Input 3 1 N 3 3 1 1 WL NR * 1 2 WLF NR ER * 1 3 NL ER * 2 1 SL WR NF * 2 2 SL WF ELF * 2 3 SF ...
- spring事务,TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
在aop配置事务控制或注解式控制事务中,try...catch...会使事务失效,可在catch中抛出运行时异常throw new RuntimeException(e)或者手动回滚Transacti ...
- [转]C# 位域[flags]
.NET中的枚举我们一般有两种用法,一是表示唯一的元素序列,例如一周里的各天:还有就是用来表示多种复合的状态.这个时候一般需要为枚举加上[Flags]特性标记为位域,例如: [Flags] enu ...
- Pyhton学习——Day8
###########################################max函数#################################################### ...
- js在当前日期基础上,加1天 3天 7天 15天
需求 点击保障期的天数 根据起始时间算出结束时间 代码 //点击保障期触发的方法 periodChange(val,id){ this.activeNumperiod=val this.submitD ...
- (2)RDD的基本操作
一.map操作,map(Transform) 二.collect操作,collect(Action) 三.使用PairRDD来做计算,类似key-value结构 采用groupByKey来.将资料按照 ...
- Multipartfile与File类型相互转换
特殊情况下需要做转换 1.M转F File file = new File(path); FileUtils.copyInputStreamToFile(multipartFile.getInputS ...
- python中return和print的区别(详细)
huskiesir最近在研究python哈,今天纠结一个问题,那就是return和print的区别,都是可以输出结果的,到底有啥区别呀?二话不多说,看下面的例子. #代码1: def break_wo ...
- 2019-03-28 SQL Server Pivot
--现在我们是用PIVOT函数将列[WEEK]的行值转换为列,并使用聚合函数Count(TotalPrice)来统计每一个Week列在转换前有多少行数据,语句如下所示 select * from Sh ...