mybatis学习
- 官网:https://mybatis.org/mybatis-3/zh/configuration.html
- 什么是mybatis
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- 持久化
- 持久层就是将程序的数据在持久层状态和瞬时状态转化的过程
- 内容:断电即失
- 数据库(jdbc),io文件持久化
- 持久层
- 完成持久化工作的代码块
- 层界限十分明显
- mybatis作用
MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及对结果集的检索封装。MyBatis可以使用简单的XML或注解用于配置和原始映射,将接口和Java的POJO(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
- 使用
- 建库
- 建项目
- 导入依赖
-
- 配置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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <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> <mappers> <mapper resource="org/mybatis/example/BlogMapper.xml"/> </mappers> </configuration>
-
- 工具类(也可以不用写,直接配置在mybatis-config.xml里面)
-
- 创建xxxMapper.xml文件,放在Dao的同包,id为dao中的方法名
-
- 直接调用dao类
- 增删改查
//查找 <select id="selectPerson" parameterType="int" parameterMap="deprecated" resultType="hashmap" resultMap="personResultMap" flushCache="false" useCache="true" timeout="10" fetchSize="256" statementType="PREPARED" resultSetType="FORWARD_ONLY"> //插入 <insert id="insertAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" keyProperty="" keyColumn="" useGeneratedKeys="" timeout="20"> //修改 <update id="updateAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20"> //删除 <delete id="deleteAuthor" parameterType="domain.blog.Author" flushCache="true" statementType="PREPARED" timeout="20">
示例
<insert id="insertAuthor"> insert into Author (id,username,password,email,bio) values (#{id},#{username},#{password},#{email},#{bio}) </insert> <update id="updateAuthor"> update Author set username = #{username}, password = #{password}, email = #{email}, bio = #{bio} where id = #{id} </update> <delete id="deleteAuthor"> delete from Author where id = #{id} </delete>
- 配置解析
<?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> <!-- 属性:定义配置外在化 --> <properties></properties> <!-- 设置:定义mybatis的一些全局性设置 --> <settings> <!-- 具体的参数名和参数值 --> <setting name="" value=""/> </settings> <!-- 类型名称:为一些类定义别名 --> <typeAliases></typeAliases> <!-- 类型处理器:定义Java类型与数据库中的数据类型之间的转换关系 --> <typeHandlers></typeHandlers> <!-- 对象工厂 --> <objectFactory type=""></objectFactory> <!-- 插件:mybatis的插件,插件可以修改mybatis的内部运行规则 --> <plugins> <plugin interceptor=""></plugin> </plugins> <!-- 环境:配置mybatis的环境 --> <environments default=""> <!-- 环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量 --> <environment id=""> <!-- 事务管理器 --> <transactionManager type=""></transactionManager> <!-- 数据源 --> <dataSource type=""></dataSource> </environment> </environments> <!-- 数据库厂商标识 --> <databaseIdProvider type=""></databaseIdProvider> <!-- 映射器:指定映射文件或者映射类 --> <mappers></mappers> </configuration>
- resultMap(结果集映射)解决属性名与字段名不一致的问题
<resultMap id="BaseResultMap" type="com.entity.Account"> <id column="id" jdbcType="VARCHAR" property="id" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="money" jdbcType="DOUBLE" property="money" /> </resultMap> <select id="sel" resultMap="accountResultMap"> select id,name,money from account where id = #{id} </select>
- 日志
- log4j
# 全局日志配置 log4j.rootLogger=ERROR, stdout # MyBatis 日志配置 log4j.logger.org.mybatis.example.BlogMapper=TRACE # 控制台输出 log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
- stdout_logging
<configuration> <settings> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> </configuration>
- 注解开发
@Select("select * from user where id = #{id}") User findById(@Param("id") long id); @Select("select * from user where name = #{name}") User findByName(@Param("name") String name); @Select("select * from user where email = #{email}") User findByEmail(@Param("email") String email)
- 多对一
<resultMap id="blogResult" type="Blog"> <id property="id" column="blog_id" /> <result property="title" column="blog_title"/> <association property="author" column="blog_author_id" javaType="Author" resultMap="authorResult"/> </resultMap> <resultMap id="authorResult" type="Author"> <id property="id" column="author_id"/> <result property="username" column="author_username"/> <result property="password" column="author_password"/> <result property="email" column="author_email"/> <result property="bio" column="author_bio"/> </resultMap>
- 一对多
<resultMap id="blogResult" type="Blog"> <association property="author" column="author_id" javaType="Author" select="selectAuthor"/> </resultMap> <select id="selectBlog" resultMap="blogResult"> SELECT * FROM BLOG WHERE ID = #{id} </select> <select id="selectAuthor" resultType="Author"> SELECT * FROM AUTHOR WHERE ID = #{id} </select>
- 动态SQL
定义:动态SQL就是指根据不同的条件生成不同的SQL语句
if
这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。
<select id="findActiveBlogWithTitleLike" resultType="Blog"> SELECT * FROM BLOG WHERE state = ‘ACTIVE’ <if test="title != null"> AND title like #{title} </if> </select>
choose (when, otherwise)
trim (where, set)
foreach
SQL片段:把重复的SQL代码提取出来,重复使用
- 缓存
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置,我们对 MyBatis 3 中的缓存实现进行了许多改进。默认情况下,只启用了本地的会话缓存(一级缓存),它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:<cache/>
二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。
- 自定义缓存
看官方文档很重要
//注解
@Select("select * from user where id = #{id}")
User findById(@Param("id")long id);
@Select("select * from user where name = #{name}")
User findByName(@Param("name")String name);
@Select("select * from user where email = #{email}")
User findByEmail(@Param("email")String email)