Mybatis
1、什么是MyBatis?
MyBatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置,以及对结果的检索。MyBatis可以使用简单的xml或注解用于配置和原始映射,将接口和Java的POJO(plain oldjava objects,普通的Java对象)映射成数据库中的记录。
2、原理
每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来获得。SqlSessionFactoryBuilder对象可以通过xml配置文件,或者从Configuration类实例中来构建SqlSessionFactory对象。
3、MyBatis和SpringBoot结合
分三步,将MyBatis导入我的SpringBoot工程中:
(1)在application.porperties增加spring配置数据库URL
spring.datasource.url=jdbc:mysql://localhost:3306/fastnews?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
mybatis.config-location=classpath:mybatis-config.xml
#logging.level.root=DEBUG
spring.velocity.suffix=.html
spring.velocity.cache=false
spring.velocity.toolbox-config-location=toolbox.xml
(2)porm.xml增加依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
(3)在templates包下添加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> <!-- 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