Spring Boot 集成 MyBatis

原文连接:http://blog.csdn.net/isea533/article/details/50359390html

 

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

Spring Boot 系列

  1. Spring Boot 入门mysql

  2. Spring Boot 属性配置和使用git

  3. Spring Boot 集成MyBatisgithub

  4. Spring Boot 静态资源处理web

  5. Spring Boot - 配置排序依赖技巧spring

  6. Spring Boot - DevTools 介绍sql

Spring Boot 集成druid

druid有不少个配置选项,使用Spring Boot 的配置文件能够方便的配置druid数据库

application.yml配置文件中写上:springboot

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

 

这里经过type: com.alibaba.druid.pool.DruidDataSource配置便可!

Spring Boot 集成MyBatis

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

mybatis-spring-boot-starter

另一种方式就是仍然用相似mybatis-spring的配置方式,这种方式须要本身写一些代码,可是能够很方便的控制MyBatis的各项配置。

1、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>

 

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 

 

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

  • mybatis.config:mybatis-config.xml配置文件的路径
  • mybatis.typeHandlersPackage:扫描typeHandlers的包
  • mybatis.checkConfigLocation:检查配置文件是否存在
  • mybatis.executorType:设置执行模式(SIMPLE, REUSE, BATCH),默认为SIMPLE

2、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); } }

 

上面代码建立了一个SqlSessionFactory和一个SqlSessionTemplate,为了支持注解事务,增长了@EnableTransactionManagement注解,而且反回了一个PlatformTransactionManagerBean。

另外应该注意到这个配置中没有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; } }

 

这个配置必定要注意@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或者页面编码的设置问题。

1、Spring或页面编码问题

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

 

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

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

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

  1. <filter>
  2. <filter-name>encodingFilter</filter-name>
  3. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  4. <init-param>
  5. <param-name>encoding</param-name>
  6. <param-value>utf-8</param-value>
  7. </init-param>
  8. <init-param>
  9. <param-name>forceEncoding</param-name>
  10. <param-value>true</param-value>
  11. </init-param>
  12. </filter>
  13. <filter-mapping>
  14. <filter-name>encodingFilter</filter-name>
  15. <url-pattern>/*</url-pattern>
  16. </filter-mapping>

 

2、Web容器的问题

若是上面方案一尚未解决乱码的问题,看一下你的Web容器的问题的编码设置,好比我使用的是Tomcat,找到server.xml。

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

 

  1. <Connector port="8081" protocol="HTTP/1.1"
  2. connectionTimeout="20000"
  3. redirectPort="8443" URIEncoding="UTF-8"/>

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

 

3、数据库或者连接数据库问题

若是经过打断点看到Spring Controller接收到值中方是正常的,可是插入数据库以后就是乱码了。通常这种状况无非就是两种问题。

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

二、mysql的连接字符串加上编码参数,以下:

  1. <environments default="development">
  2. <environment id="development">
  3. <transactionManager type="JDBC"/>
  4. <dataSource type="POOLED">
  5. <property name="driver" value="com.mysql.jdbc.Driver"/>
  6. <property name="url" value="jdbc:mysql://127.0.0.1:3306/lanhuprivi?useUnicode=true&amp;characterEncoding=UTF-8"/>
  7. <property name="username" value="root"/>
  8. <property name="password" value="root"/>
  9. </dataSource>
  10. </environment>
  11. </environments>

4、Response或者Servlet乱码问题

第一种方法:

 

  1. //getWriter()方法将 输出编码设置成iso-8859-1,这样输出utf8编码字符串必然乱码
  2. PrintWriter pw = response.getWriter();
  3. //一、
  4. //response.setCharacterEncoding("UTF-8");
  5. //二、
  6. response.setContentType("text/html; charset=utf-8");
  7. pw.write(resStr);
  8. pw.flush();
  9. pw.close();

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

 

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

 

第二种方法:

 

  1. PrintWriter out = new PrintWriter(new OutputStreamWriter(new FileOutputStream(), "UTF-8"));
相关文章
相关标签/搜索