mybatis
apache的开源项目iBatis,基于java的持久层框架
1.MyBatis
是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
1.2 持久化
数据持久化
持久化就是将程序的数据在持久状态和瞬时状态转化的过程
内存:断电即失
数据库(jdbc)io文件持久层
生活:冷藏食物起来
1.3持久层
Dao,Service层,Controller层
1.完成持久化工作的代码块
2.层界限十分明显
1.4 为什么需要Mybatis?
1.方便
2.JDBC过于复杂,需要去简化
3.自动化
4.sql和代码分离,提高可维护性
2.第一个mybatis程序
1.导入依赖
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.2</version> <scope>test</scope> </dependency> </dependencies>
1.2从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
从 XML 文件中构建 SqlSessionFactory 的实例非常简单,建议使用类路径下的资源文件进行配置。 但也可以使用任意的输入流(InputStream)实例,比如用文件路径字符串或 file:// URL 构造的输入流。MyBatis 包含一个名叫 Resources 的工具类,它包含一些实用方法,使得从类路径或其它位置加载资源文件更加容易。
String resource = "org/mybatis/example/mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
1.3配置Mybatis核心配置文件mybatis-config.xml
包括获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver?useSSL=false&useUnicode&characterEncoding=UTF-8"/> <property name="url" value="jdbc:mysql://localhost:3306/wwy"/> <property name="username" value="root"/> <property name="password" value="wwy123"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/wwy//BlogMapper.xml"/> </mappers> </configuration>
1.4编写工具类
package com.wwy.utils; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
1.5编写代码
步骤(实体类->dao接口->接口实现类)
1.5.1实体类
package com.wwy.pojo; public class User { private String username,password; public User() { } public User(String username, String password) { this.username = username; this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "pojo{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; }
1.5.2dao接口(mapper)
package com.wwy.dao; import com.wwy.pojo.User; import java.util.List; public interface UserDao { List<User> getUserList(); }
1.5.3接口实现类由原来的UserDaoImpl转变为mapper.xml
<?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="org.mybatis.example.BlogMapper"> //绑定一个对应的dao/mapper接口 <select id="selectBlog" resultType="Blog"> select * from Blog where id = #{id} </select> </mapper>
1.5.4创建一个测试类()
package com.wwy.dao; import com.wwy.pojo.User; import com.wwy.utils.MybatisUtils; import org.apache.ibatis.session.SqlSession; import java.util.List; public class Test { public static void main(String[] args) { SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> userList = mapper.getUserList(); for (User user: userList) { System.out.println(user); } sqlSession.close(); } }
1.6maven中配置无法导出添加依赖
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
3.CRUD
1.namespace
namespace中的包名要和mapper接口的包名一致
2.select
选择,查询语句
id:对应的namespace中的方法名
resultType:sql语句执行的返回值
parametertype:参数类型
增删改需要提交事务
3.1 insert
void addUser(User user); <select id="addUser" parameterType="com.wwy.pojo.User"> insert into user (id,username,password)value(#{id},#{username},#{password}) </select>
3.2update
void updateUser(User user); <select id="updateUser" parameterType="com.wwy.pojo.User"> update user set username=#{username},password=#{password} where id=#{id} </select>
3.3delete
void delete(int id); <select id="delete" parameterType="int"> delete from user where id=#{id} </select>
4.配置解析
4.1环境配置(environments)
MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中, 现实情况下有多种理由需要这么做。例如,开发、测试和生产环境需要有不同的配置;或者想在具有相同 Schema 的多个生产数据库中使用相同的 SQL 映射。还有许多类似的使用场景。
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
<environments default="development"> <environment id="development"> //选择了development环境 <transactionManager type="JDBC"> <property name="..." value="..."/> </transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments>
注意一些关键点:
-
默认使用的环境 ID(比如:default="development")。
-
每个 environment 元素定义的环境 ID(比如:id="development")。
-
事务管理器的配置(比如:type="JDBC")。
-
数据源的配置(比如:type="POOLED")。
默认环境和环境 ID 顾名思义。 环境可以随意命名,但务必保证默认的环境 ID 要匹配其中一个环境 ID。
4.2事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]"):
-
JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。
-
MANAGED – 这个配置几乎没做什么。它从不提交或回滚一个连接,而是让容器来管理事务的整个生命周期(比如 JEE 应用服务器的上下文)。 默认情况下它会关闭连接。然而一些容器并不希望连接被关闭,因此需要将 closeConnection 属性设置为 false 来阻止默认的关闭行为。例如:
<transactionManager type="MANAGED"> <property name="closeConnection" value="false"/> </transactionManager>
4.3数据源(dataSource)
dataSource 元素使用标准的 JDBC 数据源接口来配置 JDBC 连接对象的资源。
-
大多数 MyBatis 应用程序会按示例中的例子来配置数据源。虽然数据源配置是可选的,但如果要启用延迟加载特性,就必须配置数据源。
有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):
UNPOOLED– 这个数据源的实现会每次请求时打开和关闭连接。虽然有点慢,但对那些数据库连接可用性要求不高的简单应用程序来说,是一个很好的选择。 性能表现则依赖于使用的数据库,对某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。UNPOOLED 类型的数据源仅仅需要配置以下 5 种属性:
-
driver
– 这是 JDBC 驱动的 Java 类全限定名(并不是 JDBC 驱动中可能包含的数据源类)。 -
url
– 这是数据库的 JDBC URL 地址。 -
username
– 登录数据库的用户名。 -
password
– 登录数据库的密码。 -
defaultTransactionIsolationLevel
– 默认的连接事务隔离级别。 -
defaultNetworkTimeout
– 等待数据库操作完成的默认网络超时时间(单位:毫秒)。查看java.sql.Connection#setNetworkTimeout()
的 API 文档以获取更多信息。
作为可选项,你也可以传递属性给数据库驱动。只需在属性名加上“driver.”前缀即可,例如:
-
driver.encoding=UTF8
这将通过 DriverManager.getConnection(url, driverProperties) 方法传递值为 UTF8
的 encoding
属性给数据库驱动。
POOLED– 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这种处理方式很流行,能使并发 Web 应用快速响应请求。
除了上述提到 UNPOOLED 下的属性外,还有更多属性用来配置 POOLED 的数据源:
-
poolMaximumActiveConnections
– 在任意时间可存在的活动(正在使用)连接数量,默认值:10 -
poolMaximumIdleConnections
– 任意时间可能存在的空闲连接数。 -
poolMaximumCheckoutTime
– 在被强制返回之前,池中连接被检出(checked out)时间,默认值:20000 毫秒(即 20 秒) -
poolTimeToWait
– 这是一个底层设置,如果获取连接花费了相当长的时间,连接池会打印状态日志并重新尝试获取一个连接(避免在误配置的情况下一直失败且不打印日志),默认值:20000 毫秒(即 20 秒)。 -
poolMaximumLocalBadConnectionTolerance
– 这是一个关于坏连接容忍度的底层设置, 作用于每一个尝试从缓存池获取连接的线程。 如果这个线程获取到的是一个坏的连接,那么这个数据源允许这个线程尝试重新获取一个新的连接,但是这个重新尝试的次数不应该超过poolMaximumIdleConnections
与poolMaximumLocalBadConnectionTolerance
之和。 默认值:3(新增于 3.4.5) -
poolPingQuery
– 发送到数据库的侦测查询,用来检验连接是否正常工作并准备接受请求。默认是“NO PING QUERY SET”,这会导致多数数据库驱动出错时返回恰当的错误消息。 -
poolPingEnabled
– 是否启用侦测查询。若开启,需要设置poolPingQuery
属性为一个可执行的 SQL 语句(最好是一个速度非常快的 SQL 语句),默认值:false。 -
poolPingConnectionsNotUsedFor
– 配置 poolPingQuery 的频率。可以被设置为和数据库连接超时时间一样,来避免不必要的侦测,默认值:0(即所有连接每一时刻都被侦测 — 当然仅当 poolPingEnabled 为 true 时适用)。
JNDI – 这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的数据源引用。这种数据源配置只需要两个属性:
-
initial_context
– 这个属性用来在 InitialContext 中寻找上下文(即,initialContext.lookup(initial_context))。这是个可选属性,如果忽略,那么将会直接从 InitialContext 中寻找 data_source 属性。 -
data_source
– 这是引用数据源实例位置的上下文路径。提供了 initial_context 配置时会在其返回的上下文中进行查找,没有提供时则直接在 InitialContext 中查找。
和其他数据源配置类似,可以通过添加前缀“env.”直接把属性传递给 InitialContext。比如:
-
env.encoding=UTF8
这就会在 InitialContext 实例化时往它的构造方法传递值为 UTF8
的 encoding
属性。
4.4属性(properties)
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。例如:
db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/wwy?useSSL=false&useUnicode&characterEncoding=UTF-8 username=root password=root
<properties resource="db.properties"> </properties>
4.5.类型(配置)别名(typeAliases)
给实体类取别名
<typeAliases> <typeAlias type="com.wwy.pojo.User" alias="User"/> </typeAliases>
每一个在包 domain.blog
中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author
的别名为 author
;若有注解,则别名为其注解值。见下面的例子:
@Alias("author") public class Author { ... }
4.6设置(settings)
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 | true | false | false |
aggressiveLazyLoading | 开启时,任一方法的调用都会加载该对象的所有延迟加载属性。 否则,每个延迟加载属性会按需加载(参考 lazyLoadTriggerMethods )。 | true | false | false (在 3.4.1 及之前的版本中默认为 true) |
multipleResultSetsEnabled | 是否允许单个语句返回多结果集(需要数据库驱动支持)。 | true | false | true |
useColumnLabel | 使用列标签代替列名。实际表现依赖于数据库驱动,具体可参考数据库驱动的相关文档,或通过对比测试来观察。 | true | false | true |
useGeneratedKeys | 允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。 | true | false | False |
autoMappingBehavior | 指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示关闭自动映射;PARTIAL 只会自动映射没有定义嵌套结果映射的字段。 FULL 会自动映射任何复杂的结果集(无论是否嵌套)。 | NONE, PARTIAL, FULL | PARTIAL |
autoMappingUnknownColumnBehavior | 指定发现自动映射目标未知列(或未知属性类型)的行为。NONE : 不做任何反应WARNING : 输出警告日志('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARN )FAILING : 映射失败 (抛出 SqlSessionException ) | NONE, WARNING, FAILING | NONE |
defaultExecutorType | 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | 设置超时时间,它决定数据库驱动等待数据库响应的秒数。 | 任意正整数 | 未设置 (null) |
defaultFetchSize | 为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。 | 任意正整数 | 未设置 (null) |
defaultResultSetType | 指定语句默认的滚动策略。(新增于 3.5.2) | FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT(等同于未设置) | 未设置 (null) |
safeRowBoundsEnabled | 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。 | true | false | False |
safeResultHandlerEnabled | 是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。 | true | false | True |
mapUnderscoreToCamelCase | 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 | true | false | False |
localCacheScope | MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。 | SESSION | STATEMENT | SESSION |
jdbcTypeForNull | 当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 | JdbcType 常量,常用值:NULL、VARCHAR 或 OTHER。 | OTHER |
lazyLoadTriggerMethods | 指定对象的哪些方法触发一次延迟加载。 | 用逗号分隔的方法列表。 | equals,clone,hashCode,toString |
defaultScriptingLanguage | 指定动态 SQL 生成使用的默认脚本语言。 | 一个类型别名或全限定类名。 | org.apache.ibatis.scripting.xmltags.XMLLanguageDriver |
defaultEnumTypeHandler | 指定 Enum 使用的默认 TypeHandler 。(新增于 3.4.5) | 一个类型别名或全限定类名。 | org.apache.ibatis.type.EnumTypeHandler |
callSettersOnNulls | 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。 | true | false | false |
returnInstanceForEmptyRow | 当返回行的所有列都是空时,MyBatis默认返回 null 。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2) | true | false | false |
logPrefix | 指定 MyBatis 增加到日志名称的前缀。 | 任何字符串 | 未设置 |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J(deprecated since 3.5.9) | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 |
proxyFactory | 指定 Mybatis 创建可延迟加载对象所用到的代理工具。 | CGLIB | JAVASSIST | JAVASSIST (MyBatis 3.3 以上) |
vfsImpl | 指定 VFS 的实现 | 自定义 VFS 的实现的类全限定名,以逗号分隔。 | 未设置 |
useActualParamName | 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1) | true | false | true |
configurationFactory | 指定一个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3) | 一个类型别名或完全限定类名。 | 未设置 |
shrinkWhitespacesInSql | 从SQL中删除多余的空格字符。请注意,这也会影响SQL中的文字字符串。 (新增于 3.5.5) | true | false | false |
defaultSqlProviderType | Specifies an sql provider class that holds provider method (Since 3.5.6). This class apply to the type (or value ) attribute on sql provider annotation(e.g. @SelectProvider ), when these attribute was omitted. | A type alias or fully qualified class name | Not set |
nullableOnForEach | Specifies the default value of 'nullable' attribute on 'foreach' tag. (Since 3.5.9) | true | false | false |
一个配置完整的 settings 元素的示例如下:
<settings> <setting name="cacheEnabled" value="true"/> <setting name="lazyLoadingEnabled" value="true"/> <setting name="multipleResultSetsEnabled" value="true"/> <setting name="useColumnLabel" value="true"/> <setting name="useGeneratedKeys" value="false"/> <setting name="autoMappingBehavior" value="PARTIAL"/> <setting name="autoMappingUnknownColumnBehavior" value="WARNING"/> <setting name="defaultExecutorType" value="SIMPLE"/> <setting name="defaultStatementTimeout" value="25"/> <setting name="defaultFetchSize" value="100"/> <setting name="safeRowBoundsEnabled" value="false"/> <setting name="mapUnderscoreToCamelCase" value="false"/> <setting name="localCacheScope" value="SESSION"/> <setting name="jdbcTypeForNull" value="OTHER"/> <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
4.7映射器(mappers)
MapperRegistry:注册绑定我们的mapper文件;
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:///
形式的 URL),或类名和包名等。例如:
<!-- 使用相对于类路径的资源引用 --> <mappers> <mapper resource="org/mybatis/builder/AuthorMapper.xml"/> <mapper resource="org/mybatis/builder/BlogMapper.xml"/> <mapper resource="org/mybatis/builder/PostMapper.xml"/> </mappers> <!-- 使用完全限定资源定位符(URL) --> <mappers> <mapper url="file:///var/mappers/AuthorMapper.xml"/> <mapper url="file:///var/mappers/BlogMapper.xml"/> <mapper url="file:///var/mappers/PostMapper.xml"/> </mappers> <!-- 使用映射器接口实现类的完全限定类名 --> <mappers> <mapper class="org.mybatis.builder.AuthorMapper"/> <mapper class="org.mybatis.builder.BlogMapper"/> <mapper class="org.mybatis.builder.PostMapper"/> </mappers> !1.接口和他的mapper配置文件要在同一个包下 2.接口和他的mapper配置文件必须同名 <!-- 将包内的映射器接口实现全部注册为映射器 --> <mappers> <package name="org.mybatis.builder"/> </mappers>
5.ResultMap
resultMap
元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets
数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap
能够代替实现同等功能的数千行代码。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
解决属性名和字段名不一致的问题
ID | username | pwd |
---|---|---|
ID | username | password |
column为数据库中的字段,property为实体类中的属性 <resultMap id="UserMap" type="User"> <result column="id property="id"/> <result column="username" property="username"/> <result column="pwd" property="password"/> </resultMap> <select id="getUserById" resultMap="UserMap"> select *from user where id=#{id} </select>
6.mybatis流程
Resources获取加载全局配置文件 | 实例化SqlSessionFactoryBuilder构造器 | 解析配置文件流XML configBuilder | configuration使用的配置信息 | sqlsessionFactory实例化 | transactional事务管理 | 创建executor执行器 | 创建sqlsession | 实现CRUD | 查看是否成功
7.日志
Mybatis 通过使用内置的日志工厂提供日志功能。内置日志工厂将会把日志工作委托给下面的实现之一:
-
SLF4J
-
Apache Commons Logging
-
Log4j 2
-
Log4j (deprecated since 3.5.9)
-
JDK logging
MyBatis 内置日志工厂基于运行时自省机制选择合适的日志工具。它会使用第一个查找得到的工具(按上文列举的顺序查找)。如果一个都未找到,日志功能就会被禁用。
不少应用服务器(如 Tomcat 和 WebShpere)的类路径中已经包含 Commons Logging,所以在这种配置环境下的 MyBatis 会把它作为日志工具,记住这点非常重要。这将意味着,在诸如 WebSphere 的环境中,它提供了 Commons Logging 的私有实现,你的 Log4J 配置将被忽略。MyBatis 将你的 Log4J 配置忽略掉是相当令人郁闷的(事实上,正是因为在这种配置环境下,MyBatis 才会选择使用 Commons Logging 而不是 Log4J)。如果你的应用部署在一个类路径已经包含 Commons Logging 的环境中,而你又想使用其它日志工具,你可以通过在 MyBatis 配置文件 mybatis-config.xml 里面添加一项 setting 来选择别的日志工具。
<configuration> <settings> ... <setting name="logImpl" value="STDOUT_LOGGING"/> ... </settings> </configuration>
7.1LOG4J的jar包
LOG4J要导jar包
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
7.2L0G4J的properties
log4j.rootLogger=DEBUG,console,file log4j.appender.Console.encoding=UTF-8 log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.Threshold=DEBUG log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=[%c]-%m%n #文件输出的相关设置 log4j.appender.file = org.apache.log4j.RollingFileAppender log4j.appender.file.File=./log/kuang.log log4j.appender.file.MaxFileSize=10mb log4j.appender.file.Threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n #日志输出级别 log4j.logger.org.mybatis=DEBUG log4j.logger.java.sql=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.ResultSet=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
7.3配置LOG4J的实现
<settings> <setting name="logImpl" value="LOG4J"/> </settings>
7.4lOG4J的简单使用
1.再要使用的类中,导入import org.apache.log4j.Logger;
2.日志对象,参数为当前类的Class;
static Logger logger = Logger.getLogger(Test.class);
7.5日志的输出级别
into,debug,error
logger.info("info:进入了test1"); logger.debug("debug:进入了test1"); logger.error("error:进入了test1");
8.分页
为什么要分页?
-
减少数据的处理量
8.1使用Limit分页
select *from user limit startIndex,pagesize; select *from user limit 1,2; startIndex为查询下标(从此下标开始查询),pagesize为查询一页有多少个数据 !如果只给一个参数,默认为查询 pagesize
8.2使用Mybatis实现分页,SQL
1.接口
List<User> getUserList2(Map<String,Integer>map);
2.Mapper.xml
<select id="getUserList2" parameterType="map" resultMap="UserMap"> select *from user limit #{startIndex},#{pagesize} </select>
3.测试
public void test2(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("startIndex",0); map.put("pagesize",2); List<User> userList2 = mapper.getUserList2(map); for (User user: userList2 ) { System.out.println(user); }
9.使用注解编程
-
注解:底层是动态代理,本质是反射。
-
1.注解在接口上实现
public interface UserMapper { @Select("Select * from student") List<User> getUsers(); }
-
2.需要在核心配置文件中绑定接口
<mappers> <mapper class="com.kuang.dao.UserMapper"/> </mappers>
9.1注解的CRUD
@Select("select * from student where id=#{id}") User getuserbyid(@Param("id")int id); @Insert("insert into student(id,name,pwd)values(#{id},#{name},#{password})") int adduser(User user); @Update("update student set name=#{name},pwd=#{password} where id=#{id}") int updata(User user); @Delete("delete from student where id=#{id}") int delete(int id);
9.2关于@Param()注解
-
基本类型的参数或者String类型,需要加上
-
引用类型不需要加
-
如果只有一个基本类型,可以忽略,但是建议都加上
-
我们在sql引用的就是我们这里的@Param()中设定的属性名
10.关于接口
关于接口理解 接口:应为定义(规范,约束)与实现(名实分离的原则)的分离 接口两类: 一:对一个个体的抽象,对应为一个抽象体; 二: 对一个个体某一方面的抽象,即形成一个抽象面; 一个体有可能有多个抽象面。
接口设计与非接口设计是针对复用技术而言。
11.多对一处理(重点)
-
例:多个学生,对应一个老师
-
对于学生,关联..多个学生,关联一个老师【多对一】
-
对于老师,集合,一个学生有很多学生【一对多】
11.1 多表查询的第一种方法(对象)
实体类
public class Student { private int id; private String name; private Teacher teacher; }
-
public class Teacher { private int id; private String name; }
-
1查询所有学生的信息
-
2根据查出来的学生的tid,寻找对应的老师(相当在嵌套查询(子查询))
<resultMap id="Student_T" type="Student"> <result column="id" property="id"/> <result column="name" property="name"/> <!-- 复杂的属性需要单独处理,对象:association 集合:collection --> <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/> </resultMap> <select id="getStudent" resultMap="Student_T"> select * from student </select> <select id="getTeacher" resultType="com.wwy.pojo.Teacher"> select * from teacher where id=#{tid} </select>
11.2 多表查询的第二种方法
-
根据结果去嵌套查询
<select id="getStudent2" resultMap="Student_t"> select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id; </select> <resultMap id="Student_t" type="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <association property="teacher" javaType="Teacher"> <result property="name" column="tname"/> </association> </resultMap>
12.一对多处理
-
对于老师,集合,一个学生有很多学生【一对多】
实体类
public class Student { private int id; private String name; private int tid; }
public class Teacher { private int id; private String name; private List<Student> students; }
根据结果嵌套查询(联表查询)
<select id="getTeacher" resultMap="Teacher_s"> select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id and t.id=#{tid} </select> <resultMap id="Teacher_s" type="Teacher"> <result property="id" column="tid"/> <result property="name" column="tname"/> <collection property="students" ofType="Student"> <result property="id" column="sid"/> <result property="name" column="sname"/> <result property="tid" column="tid"/> </collection> </resultMap>
子查询(嵌套查询)
<select id="getTeacher2" resultMap="Teacher_s1"> select * from teacher where id=#{tid}; </select> <resultMap id="Teacher_s1" type="Teacher"> <collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudentByTeacherID" /> </resultMap> <select id="getStudentByTeacherID" resultType="Student"> select * from student where tid=#{tid} </select>
13.多对一和一对多小结
-
1.关联-association【多对一】
-
2.集合-collection【一对多】
-
3.javaType & ofType
1.javaType:用来指定实体类中的属性类型
2.ofType:用来指定映射到List或者集合中的POJO类型,泛型中的约束类型!
14.动态SQL
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
-
if
-
choose (when, otherwise)
-
trim (where, set)
-
foreach
14.1环境搭配
1.编写实体类
public class Blog { private String id; private String title; private String author; private Date createTime; private int views; }
2.编写对应的Mapper.xml文件和映射上Mapper.xml
14.2 IF
<select id="querBlogIF" parameterType="map" resultType="Blog"> select * from blog where 1=1 <if test="title!=null"> and title=#{title} </if> <if test="author!=null"> and author=#{author} </if> </select>
public void queryBlogIF(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); // map.put("title","java"); map.put("author","狂神说"); List<Blog> blogs = mapper.querBlogIF(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
14.3 choose (when, otherwise)
<select id="querBlogChoose" parameterType="map" resultType="Blog"> select * from blog <where> <choose> <when test="title!=null"> title=#{title} </when> <when test="author"> and author=#{author} </when> <otherwise> and views=#{views} </otherwise> </choose> </where> </select>
14.4 trim(where、set)
where
select * from blog <where> <if test="title!=null"> and title=#{title} </if> <if test="author!=null"> and author=#{author} </if> </where> </select>
set
<select id="updateBlog" parameterType="map"> update blog <set> <if test="title!=null"> title=#{title}, </if> <if test="author!=null"> author=#{author} </if> where id=#{id} </set> </select>
SQL片段
有的時候,我們可能会将一些功能的部分抽取出来,方便复用
1.使用SQL标签抽取公共的部分
<sql id="IF-title_author"> <if test="title!=null"> and title=#{title} </if> <if test="author!=null"> and author=#{author} </if> </sql>
2.在需要使用的地方使用include标签引用即可
<select id="queryBlogIF" parameterType="map" resultType="Blog"> select * from blog <where> <include refid="IF-title_author"/> </where> </select>
注意点“
-
最好基于单表来定义SQL片段
-
不要存在where标签
Foreach
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。
<select id="queryBlogForeach" parameterType="map" resultType="Blog"> select * from blog <where> <foreach collection="ids" item="id" open="and (" close=")" separator="or"> id=#{id} </foreach> </where> </select>
public void queryBlogForEach(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); HashMap map = new HashMap(); ArrayList<Integer> ids = new ArrayList<Integer>(); ids.add(1); ids.add(2); ids.add(3); map.put("ids",ids); List<Blog> blogs = mapper.queryBlogForeach(map); for (Blog blog : blogs) { System.out.println(blog); } sqlSession.close(); }
缓存
1.什么是缓存
-
存在内存中的临时数据
-
将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
2.为什么使用缓存
-
减少和数据库的交互次数,减少系统开销,提高系统效率
3.什么样的数据能使用缓存
-
经常查询并且不经常改变的数据
Mybatis缓存
-
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。
-
Mybatis系统默认定义了两级缓存:一级和二级缓存,要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:<cache/>
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。(SqlSession级别的缓存)
-
二级缓存需要手动开启和配置,基于namespace级别的缓存
-
Mybatis定义了Cache,我们通过实现接口来定义二级缓存
基本上就是这样。这个简单语句的效果如下:
-
映射语句文件中的所有 select 语句的结果将会被缓存。
-
映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
-
缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
-
缓存不会定时进行刷新(也就是说,没有刷新间隔)。
-
缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
-
缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
可用的清除策略有:
-
LRU
– 最近最少使用:移除最长时间不被使用的对象。 -
FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。 -
SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。 -
WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
默认的清除策略是 LRU。
一级缓存
缓存失效的情况:
-
1.查询不同的东西
-
2.增删改操作,可能会改变原来的数据,所以必定刷新缓存
-
3.查询不同的Mapper.xml
-
4.手动清理缓存
二级缓存
开启步骤
1.开启全局缓存
<setting name="cacheEnabled" value="true"/>
2.在要使用二级缓存的Mapper中开启
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
1.问题:我们需要将实体类序列化(读)/* 反序列化为(写)*/,否则会报错或者<cache/>里添加只读readOnly="true"
小结:
-
只要开启了二级缓存,在同一个Mapper下就有效
-
所有的数据都会先放在一级缓存中
-
只有当会话提交,或者关闭的失候,才会提交到二级缓存中。
缓存原理
一级缓存关闭后缓存内容会放在二级缓存中
缓存顺序
1.先看二级缓存中有没有内容
2.再看一级缓存中有没有内柔
3.查询数据库