一、使用mybatis-spring-boot-starter

1、添加依赖
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency>
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" ?>
<!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
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" ?>
<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依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
mybatis-spring等依赖
<!-- 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配置文件
@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
# mybatis
# boot与mybits
# SpringBoot集成mybatis
# springboot集成mybatis-maven插件自动生成pojo的详细教程
# 详解springboot集成mybatis xml方式
# 创建SpringBoot工程并集成Mybatis的方法
# SpringBoot集成MyBatis的分页插件PageHelper实例代码
# springboot集成mybatis实例代码
# springboot集成Mybatis的详细教程
# 配置文件
# 比较容易
# 启动时
# 大家多多
# xixicat
# modules
# dao
# Configuration
# PropertySource
# selectOne
# strong
# true
# file
# MybatisConfig
# ignoreResourceNotFound
# PropertySources
# database
# classpath
# return
# package
相关文章:
怀化网站制作公司,怀化新生儿上户网上办理流程?
,想在网上投简历,哪几个网站比较好?
建站之星各版本价格是多少?
网站制作模板下载什么软件,ppt模板免费下载网站?
百度网页制作网站有哪些,谁能告诉我百度网站是怎么联系?
Python文件管理规范_工程实践说明【指导】
,在苏州找工作,上哪个网站比较好?
小型网站建站如何选择虚拟主机?
如何在VPS电脑上快速搭建网站?
油猴 教程,油猴搜脚本为什么会网页无法显示?
制作网站哪家好,cc、.co、.cm哪个域名更适合做网站?
建站之星安装后界面空白如何解决?
如何快速打造个性化非模板自助建站?
如何选择适配移动端的WAP自助建站平台?
如何通过二级域名建站提升品牌影响力?
小程序网站制作需要准备什么资料,如何制作小程序?
TestNG的testng.xml配置文件怎么写
潮流网站制作头像软件下载,适合母子的网名有哪些?
如何制作一个表白网站视频,关于勇敢表白的小标题?
头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?
Bpmn 2.0的XML文件怎么画流程图
nginx修改上传文件大小限制的方法
装修招标网站设计制作流程,装修招标流程?
建站之星价格显示格式升级,你的预算足够吗?
香港服务器租用费用高吗?如何避免常见误区?
php能控制zigbee模块吗_php通过串口与cc2530 zigbee通信【介绍】
西安大型网站制作公司,西安招聘网站最好的是哪个?
长春网站建设制作公司,长春的网络公司怎么样主要是能做网站的?
浙江网站制作公司有哪些,浙江栢塑信息技术有限公司定制网站做的怎么样?
如何快速配置高效服务器建站软件?
如何在建站之星网店版论坛获取技术支持?
天津个人网站制作公司,天津网约车驾驶员从业资格证官网?
如何选择CMS系统实现快速建站与SEO优化?
个人摄影网站制作流程,摄影爱好者都去什么网站?
猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?
如何在阿里云高效完成企业建站全流程?
建站之星上传入口如何快速找到?
保定网站制作方案定制,保定招聘的渠道有哪些?找工作的人一般都去哪里看招聘信息?
javascript中的try catch异常捕获机制用法分析
建站之星如何防范黑客攻击与数据泄露?
江苏网站制作公司有哪些,江苏书法考级官方网站?
如何获取免费开源的自助建站系统源码?
c++怎么编写动态链接库dll_c++ __declspec(dllexport)导出与调用【方法】
制作充值网站的软件,做人力招聘为什么要自己交端口钱?
网站制作公司,橙子建站是合法的吗?
如何快速登录WAP自助建站平台?
如何撰写建站申请书?关键要点有哪些?
网站制作培训多少钱一个月,网站优化seo培训课程有哪些?
建站之星logo尺寸如何设置最合适?
如何在自有机房高效搭建专业网站?
*请认真填写需求信息,我们会在24小时内与您取得联系。