示例的各个文件如下:

在pom里加了mybatis的依赖后,在application.properties加上:

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=**
spring.datasource.password=** mybatis.mapperLocations=classpath*:mapper/*Mapper.xml
mybatis.typeAliasesPackage=com.example.springmybatis.model
mybatis.config-location=classpath:mybatis-config.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>
<!-- 参数设置 -->
<settings>
<!-- 这个配置使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载 -->
<setting name="lazyLoadingEnabled" value="true" />
<!-- 当启用时,有延迟加载属性的对象在被调用时将会完全加载任意属性。否则,每种属性将会按需要加载 -->
<setting name="aggressiveLazyLoading" value="true" />
<!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动) -->
<setting name="multipleResultSetsEnabled" value="true" />
<!-- 使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动 -->
<setting name="useColumnLabel" value="true" />
<!-- 允许JDBC支持生成的键。需要适合的驱动。如果设置为true则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如Derby) -->
<setting name="useGeneratedKeys" value="true" />
<!-- 指定MyBatis如何自动映射列到字段/属性。PARTIAL只会自动映射简单,没有嵌套的结果。FULL会自动映射任意复杂的结果(嵌套的或其他情况) -->
<setting name="autoMappingBehavior" value="PARTIAL" />
<!--当检测出未知列(或未知属性)时,如何处理,默认情况下没有任何提示,这在测试的时候很不方便,不容易找到错误。
NONE : 不做任何处理 (默认值)
WARNING : 警告日志形式的详细信息
FAILING : 映射失败,抛出异常和详细信息
-->
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<!-- 配置默认的执行器。SIMPLE执行器没有什么特别之处。REUSE执行器重用预处理语句。BATCH执行器重用语句和批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 -->
<setting name="defaultStatementTimeout" value="25000" />
<!--设置查询返回值数量,可以被查询数值覆盖 -->
<setting name="defaultFetchSize" value="100"/>
<!-- 允许在嵌套语句中使用分页-->
<setting name="safeRowBoundsEnabled" value="false"/>
<!--是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。-->
<setting name="mapUnderscoreToCamelCase" value="false"/>
<!--MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。-->
<setting name="localCacheScope" value="SESSION"/>
<!-- 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR OTHER。-->
<setting name="jdbcTypeForNull" value="OTHER"/>
<!-- 指定哪个对象的方法触发一次延迟加载。-->
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings> <!-- 别名定义 -->
<typeAliases>
<typeAlias alias="pageAccessURL" type="com.lgm.mybatis.model.PageAccessURL" />
</typeAliases> <!--自定义类型处理器 -->
<typeHandlers>
<!-- <typeHandler handler="com.xhm.util.BooleanTypeHandlder" /> -->
<!--扫描整个包下的自定义类型处理器-->
<package name="com.xhm.util"/>
</typeHandlers> <!--plugins插件之 分页拦截器 -->
<plugins>
<plugin interceptor="com.xhm.util.PageInterceptor"></plugin>
</plugins> <!--配置environment环境-->
<environments default="development">
<!-- 环境配置1,每个SqlSessionFactory对应一个环境 -->
<environment id="development1">
<!-- 事务配置 type= JDBC、MANAGED 1.JDBC:这个配置直接简单使用了JDBC的提交和回滚设置。它依赖于从数据源得到的连接来管理事务范围。
2.MANAGED:这个配置几乎没做什么。它从来不提交或回滚一个连接。而它会让容器来管理事务的整个生命周期(比如Spring或JEE应用服务器的上下文)。 默认情况下它会关闭连接。然而一些容器并不希望这样,因此如果你需要从连接中停止它,将closeConnection属性设置为false -->
<transactionManager type="JDBC" />
<!-- <transactionManager type="MANAGED">
<property name="closeConnection" value="false"/>
</transactionManager> -->
<!-- 数据源类型:type = UNPOOLED、POOLED、JNDI 1.UNPOOLED:这个数据源的实现是每次被请求时简单打开和关闭连接。它有一点慢,这是对简单应用程序的一个很好的选择,因为它不需要及时的可用连接。
不同的数据库对这个的表现也是不一样的,所以对某些数据库来说配置数据源并不重要,这个配置也是闲置的 2.POOLED:这是JDBC连接对象的数据源连接池的实现,用来避免创建新的连接实例时必要的初始连接和认证时间。
这是一种当前Web应用程序用来快速响应请求很流行的方法。 3.JNDI:这个数据源的实现是为了使用如Spring或应用服务器这类的容器,容器可以集中或在外部配置数据源,然后放置一个JNDI上下文的引用 -->
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/xhm" />
<property name="username" value="root" />
<property name="password" value="root" />
<!-- 默认连接事务隔离级别 <property name="defaultTransactionIsolationLevel" value=""
/> -->
</dataSource>
</environment> <!-- 环境配置2 -->
<environment id="development2">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/xhm" />
<property name="username" value="root" />
<property name="password" value="root" />
<!-- 在任意时间存在的活动(也就是正在使用)连接的数量 -->
<property name="poolMaximumActiveConnections" value="10" />
<!-- 任意时间存在的空闲连接数 -->
<property name="poolMaximumIdleConnections" value="5" />
<!-- 在被强制返回之前,池中连接被检查的时间 -->
<property name="poolMaximumCheckoutTime" value="20000" />
<!-- 这是给连接池一个打印日志状态机会的低层次设置,还有重新尝试获得连接,这些情况下往往需要很长时间(为了避免连接池没有配置时静默失败) -->
<property name="poolTimeToWait" value="20000" />
<!-- 发送到数据的侦测查询,用来验证连接是否正常工作,并且准备接受请求。 -->
<property name="poolPingQuery" value="NO PING QUERY SET" />
<!-- 这是开启或禁用侦测查询。如果开启,你必须用一个合法的SQL语句(最好是很快速的)设置poolPingQuery属性 -->
<property name="poolPingEnabled" value="false" />
<!-- 这是用来配置poolPingQuery多次时间被用一次。这可以被设置匹配标准的数据库连接超时时间,来避免不必要的侦测 -->
<property name="poolPingConnectionsNotUsedFor" value="0" />
</dataSource>
</environment> <!-- 环境配置3 -->
<environment id="development3">
<transactionManager type="JDBC" />
<dataSource type="JNDI">
<property name="data_source" value="java:comp/env/jndi/mybatis" />
<property name="env.encoding" value="UTF8" />
<!-- <property name="initial_context" value=""/> <property name="env.encoding"
value="UTF8"/> -->
</dataSource>
</environment>
</environments> <!-- 映射文件,mapper的配置文件 -->
<mappers>
<!--直接映射到相应的mapper文件-->
<mapper resource="com/xhm/mapper/UserMapper.xml"/>
<!--扫描包路径下所有xxMapper.xml文件-->
<package name="com.xhm.mapper"/>
</mappers>
</configuration>

在项目中,一般不需要特殊配置,主要是开启驼峰命名。我使用的一般配置是:

<?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> <settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings> <!-- Continue going here --> </configuration>

在resource文件夹新建CountryMapper.xml,用xml配置sql。内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.springmybatis.mapper.CountryMapper">
<select id="selectAll" resultType="Country">
select id,countryname,countrycode from country
</select>
</mapper>

controller中使用

新建mapper包,创建CountryMapper接口文件,内容如下:

package com.example.springmybatis.mapper;

import com.example.springmybatis.model.Country;
import org.apache.ibatis.annotations.Mapper; import java.util.List; @Mapper
public interface CountryMapper {
List<Country> selectAll();
}

同时新建controller和service包和类,如下:

controoller:

package com.example.springmybatis.controller;

import com.alibaba.fastjson.JSON;
import com.example.springmybatis.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class countryController { @Autowired
private CountryService countryService; @RequestMapping("/selectAll")
public String selectAll(){
return JSON.toJSONString(countryService.selectAll());
}
}

service:

package com.example.springmybatis.service;

import com.example.springmybatis.mapper.CountryMapper;
import com.example.springmybatis.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.util.List; @Service
public class CountryService { @Autowired
private CountryMapper countryMapper; public List<Country> selectAll(){
return countryMapper.selectAll();
}
}

model就省略了,只有id,countryName,countryCode三个属性。

Spring Boot配置Mybatis的更多相关文章

  1. spring boot配置mybatis和事务管理

    spring boot配置mybatis和事务管理 一.spring boot与mybatis的配置 1.首先,spring boot 配置mybatis需要的全部依赖如下: <!-- Spri ...

  2. Spring boot 配置 mybatis xml和动态SQL 分页配置

    更新时间 2018年4月30日23:27:07 1.pom.xml <?xml version="1.0" encoding="UTF-8"?> & ...

  3. spring boot系列(六)spring boot 配置mybatis(xml简化版)

    orm框架的本质是简化编程中操作数据库的编码,发展到现在基本上就剩两家了,一个是宣称可以不用写一句SQL的hibernate,一个是可以灵活调试动态sql的mybatis,两者各有特点,在企业级系统开 ...

  4. spring boot 配置mybatis plus 控制台打印sql

    spring boot 版本2.1.5 mybatis plus 版本3.1.1 aplication.properties中添加 logging.level.com.demo.system.mapp ...

  5. spring boot + druid + mybatis + atomikos 多数据源配置 并支持分布式事务

    文章目录 一.综述 1.1 项目说明 1.2 项目结构 二.配置多数据源并支持分布式事务 2.1 导入基本依赖 2.2 在yml中配置多数据源信息 2.3 进行多数据源的配置 三.整合结果测试 3.1 ...

  6. spring boot集成mybatis(3) - mybatis generator 配置

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

  7. 太妙了!Spring boot 整合 Mybatis Druid,还能配置监控?

    Spring boot 整合 Mybatis Druid并配置监控 添加依赖 <!--druid--> <dependency> <groupId>com.alib ...

  8. Spring Boot 整合 Mybatis 实现 Druid 多数据源详解

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! “清醒时做事,糊涂时跑步,大怒时睡觉,独处时思考” 本文提纲一.多数据源的应用场景二.运行 sp ...

  9. 使用intelliJ创建 spring boot + gradle + mybatis站点

    Spring boot作为快速入门是不错的选择,现在似乎没有看到大家写过spring boot + gradle + mybatis在intellij下的入门文章,碰巧.Net同事问到,我想我也可以写 ...

随机推荐

  1. 背水一战 Windows 10 (49) - 控件(集合类): Pivot, Hub

    [源码下载] 背水一战 Windows 10 (49) - 控件(集合类): Pivot, Hub 作者:webabcd 介绍背水一战 Windows 10 之 控件(集合类) Pivot Hub 示 ...

  2. Lerning Entity Framework 6 ------ Introduction to TPT

    Sometimes, you've created a table for example named Person. Just then, you want to add some extra in ...

  3. 友链&&日记

    上面友链,下面日记 友人链 最喜欢galgameの加藤聚聚 初三一本&&\(ACG\)姿势比我还丰厚的yx巨巨 更喜欢galgame的shadowice czx ZigZag胖胖 文文 ...

  4. SpringCloud之Eureka集群

    前面我们介绍了SpringCloud注册中心Eureka,但是存在一个单点故障的问题,一个注册中心远远不能满足实际的生产环境,现在我们介绍一下如何搭建一个Eureka集群. 一:集群环境搭建 我们先建 ...

  5. 在centos使用redis几个坑

    问题来源 最近公司的平台需要做一些分布式的规划,其中会话我们打算用redis来存储,因为之前也有了解过redis,但都是在windows上使用,为了发挥redis的优势,这次我们打算直接在Linux上 ...

  6. drf-视图的理解

    1. 类视图 写视图的步骤:      1. 数据库查询,   2. 构建序列化器, 进行序列化操作, 返回数据 一. 两大基类    >1 APIView   (以常规的方法实现get  po ...

  7. Redis---事务和Wtach

    1. 概述 Redis通过 MULTI, EXEC / WATCH 等命令来实现事务. 事务提供一种将多个命令请求打包, 然后一次性.按顺序的执行多个命令的机制. 并且在事务执行期间, 服务器不会中断 ...

  8. 解决微信小程序要求的TLS版本必须大于等于1.2的问题

    一.环境: CentOS 6.8 nginx 1.6.0 php 7.0.10 二.背景 最近开发一个小程序,而小程序对后台接口服务器的要求是: 1.请求域名在request合法域名中 2.基于 ht ...

  9. (原创)Callable、FutureTask中阻塞超时返回的坑点

    直接上代码 import java.util.concurrent.Callable; public class MyCallable implements Callable<String> ...

  10. 使用pymysql

    安装 pip3 install pymysql 连接.执行sql.关闭(游标) import pymysql mysql_connect_dict={ 'host':'127.0.0.1', 'por ...