您的位置:首页 > 编程语言 > Java开发

Spring Boot 集成 MyBatis

2017-10-12 14:53 381 查看
原文链接:http://blog.csdn.net/isea533/article/details/50359390

在集成MyBatis前,我们先配置一个druid数据源。

Spring Boot 系列

Spring Boot 入门

Spring Boot 属性配置和使用

Spring Boot 集成MyBatis

Spring Boot 静态资源处理

Spring Boot - 配置排序依赖技巧

Spring Boot - DevTools 介绍

Spring Boot 集成druid

druid
有很多个配置选项,使用Spring Boot 的配置文件可以方便的配置
druid


application.yml
配置文件中写上:

spring:
datasource:
name: test
url: jdbc:mysql://192.168.16.137:3306/test
username: root
password:
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
[/code]

这里通过
type: com.alibaba.druid.pool.DruidDataSource
配置即可!

Spring Boot 集成MyBatis

Spring Boot 集成MyBatis有两种方式,一种简单的方式就是使用MyBatis官方提供的:


另外一种方式就是仍然用类似
mybatis-spring
的配置方式,这种方式需要自己写一些代码,但是可以很方便的控制MyBatis的各项配置。

一、mybatis-spring-boot-starter方式

pom.xml
中添加依赖:

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
[/code]

mybatis-spring-boot-starter
依赖树如下:



其中
mybatis
使用的3.3.0版本,可以通过:
<mybatis.version>3.3.0</mybatis.version>
属性修改默认版本。
mybatis-spring
使用版本1.2.3,可以通过:
<mybatis-spring.version>1.2.3</mybatis-spring.version>
修改默认版本。

application.yml
中增加配置:

mybatis:
mapperLocations: classpath:mapper/*.xml
typeAliasesPackage: tk.mapper.model
[/code]

除了上面常见的两项配置,还有:

mybatis.config:mybatis-config.xml配置文件的路径

mybatis.typeHandlersPackage:扫描typeHandlers的包

mybatis.checkConfigLocation:检查配置文件是否存在

mybatis.executorType:设置执行模式(
SIMPLE, REUSE, BATCH
),默认为
SIMPLE


二、mybatis-spring方式

这种方式和平常的用法比较接近。需要添加
mybatis
依赖和
mybatis-spring
依赖。

然后创建一个
MyBatisConfig
配置类:

/**
* MyBatis基础配置
*
* @author liuzh
* @since 2015-12-19 10:11
*/
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {

@Autowired
DataSource dataSource;

@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("tk.mybatis.springboot.model");

//分页插件
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);

//添加插件
bean.setPlugins(new Interceptor[]{pageHelper});

//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}

@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}

@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
[/code]

上面代码创建了一个
SqlSessionFactory
和一个
SqlSessionTemplate
,为了支持注解事务,增加了
@EnableTransactionManagement
注解,并且反回了一个
PlatformTransactionManager
Bean。

另外应该注意到这个配置中没有
MapperScannerConfigurer
,如果我们想要扫描MyBatis的Mapper接口,我们就需要配置这个类,这个配置我们需要单独放到一个类中。

/**
* MyBatis扫描接口
*
* @author liuzh
* @since 2015-12-19 14:46
*/
@Configuration
//TODO 注意,由于MapperScannerConfigurer执行的比较早,所以必须有下面的注解
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper");
return mapperScannerConfigurer;
}

}
[/code]

这个配置一定要注意
@AutoConfigureAfter(MyBatisConfig.class)
,必须有这个配置,否则会有异常。原因就是这个类执行的比较早,由于
sqlSessionFactory
还不存在,后续执行出错。

做好上面配置以后就可以使用MyBatis了。

关于分页插件和通用Mapper集成

分页插件作为插件的例子在上面代码中有。

通用Mapper配置实际就是配置
MapperScannerConfigurer
的时候使用
tk.mybatis.spring.mapper.MapperScannerConfigurer
即可,配置属性使用
Properties


Spring Boot集成MyBatis的基础项目

我上传到github一个采用第二种方式的集成项目,并且集成了分页插件和通用Mapper,项目包含了简单的配置和操作,仅作为参考。

项目地址:https://github.com/abel533/MyBatis-Spring-Boot

分页插件和通用Mapper的相关信息可以通过上面地址找到。
http://blog.csdn.net/zhangzuyuanbest/article/details/53453792
彻底解决Spring MVC+Mybatis中文乱码问题

Java对于新手最容易出现的问题就是中文乱码的问题。今天我就来总结一下彻底解决Spring mvc+Mybatis中文乱码的方案。

首先要看打一断点看一下Controller接收到参数值是否正常。如果不正常多半是因为Spring或者页面编码的设置问题。

一、Spring或页面编码问题

在JSP页面第一行加上下面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

因为Springmvc采用默认的编码(ISO-8859-1)进行解析参数, 这时就会出现乱码问题。

在Web.xml加上Spring编码转换过滤器filter。

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>utf-8</param-value>

</init-param>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

二、Web容器的问题

如果上面方案一还没有解决乱码的问题,看一下你的Web容器的问题的编码设置,比如我使用的是Tomcat,找到server.xml。



可以看到Connector没有设置编码。加上编码属性URIEncoding,如下:

<Connector port="8081" protocol="HTTP/1.1"

connectionTimeout="20000"

redirectPort="8443" URIEncoding="UTF-8"/>

端口我使用是8081。上面主要是解决GET请求中文乱码的问题。

三、数据库或者链接数据库问题

如果通过打断点看到Spring Controller接收到值中方是正常的,但是插入数据库之后就是乱码了。一般这种情况无非就是两种问题。

1、数据库编码、表编码、列编码依次检查是否是UTF-8编码

2、mysql的链接字符串加上编码参数,如下:

<environments default="development">

<environment id="development">

<transactionManager type="JDBC"/>

<dataSource type="POOLED">

<property name="driver" value="com.mysql.jdbc.Driver"/>

<property name="url" value="jdbc:mysql://127.0.0.1:3306/lanhuprivi?useUnicode=true&characterEncoding=UTF-8"/>

<property name="username" value="root"/>

<property name="password" value="root"/>

</dataSource>

</environment>

</environments>

四、Response或者Servlet乱码问题

第一种方法:

//getWriter()方法将 输出编码设置成iso-8859-1,这样输出utf8编码字符串必然乱码

PrintWriter pw = response.getWriter();

//1、

//response.setCharacterEncoding("UTF-8");

//2、

response.setContentType("text/html; charset=utf-8");

pw.write(resStr);

pw.flush();

pw.close();

setContentType 和 setCharacterEncoding两方法中设定characterEncoding的方法对服务器效果一致,不需要反复调用。

在输出文本内容时,采用response.setContentType("text/html; charset=utf-8");似乎更为方便。

第二种方法:

PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(), "UTF-8"));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: