一、使用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
相关文章:
打鱼网站制作软件,波克捕鱼官方号怎么注册?
网站制作的步骤包括,正确网址格式怎么写?
网站制作大概多少钱一个,做一个平台网站大概多少钱?
C#如何在一个XML文件中查找并替换文本内容
音响网站制作视频教程,隆霸音响官方网站?
手机网站制作平台,手机靓号代理商怎么制作属于自己的手机靓号网站?
c# F# 的 MailboxProcessor 和 C# 的 Actor 模型
网站制作公司,橙子建站是合法的吗?
成都品牌网站制作公司,成都营业执照年报网上怎么办理?
如何快速生成专业多端适配建站电话?
如何确保西部建站助手FTP传输的安全性?
如何通过NAT技术实现内网高效建站?
广州网站建站公司选择指南:建站流程与SEO优化关键词解析
如何快速搭建FTP站点实现文件共享?
如何快速生成ASP一键建站模板并优化安全性?
C#如何使用XPathNavigator高效查询XML
金*站制作公司有哪些,金华教育集团官网?
Android滚轮选择时间控件使用详解
制作网站的公司有哪些,做一个公司网站要多少钱?
c++怎么编写动态链接库dll_c++ __declspec(dllexport)导出与调用【方法】
深圳网站制作培训,深圳哪些招聘网站比较好?
建站之星如何快速生成多端适配网站?
如何获取上海专业网站定制建站电话?
公司门户网站制作公司有哪些,怎样使用wordpress制作一个企业网站?
图片制作网站免费软件,有没有免费的网站或软件可以将图片批量转为A4大小的pdf?
如何确认建站备案号应放置的具体位置?
建站之星代理如何优化在线客服效率?
C#怎么创建控制台应用 C# Console App项目创建方法
红河网站制作公司,红河事业单位身份证如何上传?
如何设置并定期更换建站之星安全管理员密码?
建设网站制作价格,怎样建立自己的公司网站?
制作网站怎么制作,*游戏网站怎么搭建?
宝塔Windows建站如何避免显示默认IIS页面?
如何选购建站域名与空间?自助平台全解析
高端企业智能建站程序:SEO优化与响应式模板定制开发
如何选择高效稳定的ISP建站解决方案?
香港代理服务器配置指南:高匿IP选择、跨境加速与SEO优化技巧
已有域名和空间如何快速搭建网站?
企业微网站怎么做,公司网站和公众号有什么区别?
如何在IIS7上新建站点并设置安全权限?
重庆市网站制作公司,重庆招聘网站哪个好?
香港网站服务器数量如何影响SEO优化效果?
详解jQuery停止动画——stop()方法的使用
建站之星2.7模板:企业网站建设与h5定制设计专题
如何撰写建站申请书?关键要点有哪些?
平台云上自主建站:模板化设计与智能工具打造高效网站
如何通过多用户协作模板快速搭建高效企业网站?
建站168自助建站系统:快速模板定制与SEO优化指南
购物网站制作公司有哪些,哪个购物网站比较好?
建站之星如何实现PC+手机+微信网站五合一建站?
*请认真填写需求信息,我们会在24小时内与您取得联系。