创建Maven工程并导入坐标
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
创建实体类和Dao接口
创建MyBatis的主配置文件
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">
<!--MyBatis的主配置文件-->
<configuration>
<!--配置环境-->
<environments default="mysql">
<!-- 配置,mysql的环境-->
<environment id="mysql">
<!--配置事务类型-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的4个基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///表名"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
<mappers>
<mapper resource="映射文件全限定名"/>
</mappers>
</configuration>
创建映射配置文件
必须和dao接口的包结构相同
<?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="dao接口的全限定类名">
<!--配置查询所有-->
<select id="dao接口下的方法名" resultType="返回结果集实体类的全限定类名" parameterType="参数类型">
sql语句
</select>
</mapper>
MyBatis工具类
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//读取配置文件
InputStream is = Resources.getResourceAsStream("MyBatis-Config.xml");
//创建SqlSessionFactory工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession(true);//true为开启事务提交
}
}
资源过滤
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息。 配置文档的顶层结构如下
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
properties(属性):外部进行配置,并可以进行动态替换
可以通过引入db.properties文件属性来实现配置文件数据
<properties resource="db.properties"/>
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql:///mybatis
username=root
password=root
typeAliases(类型别名):可为 Java 类型设置一个缩写名字,它仅用于 XML 配置,意在降低冗余的全限定类名书写
<typeAliases>
<typeAlias alias="别名" type="全限定类名"/>
</typeAliases>
<mappers>
<mapper resource="cn/demo/dao/xxx.xml"/>
</mappers>
<resultMap id="映射ID" type="实体类">
<result column="数据库表中的字段名(id)" property="实体类中的属性(uid)"/>
</resultMap>
<select id="Dao接口下的方法名" parameterType="参数类型" resultMap="映射ID">
select * from user where id=#{uid};
</select>
//模糊查询名字
List<User> getLikeUser(String name);
<!--模糊查询名字-->
<select id="getLikeUser" parameterType="String" resultType="User">
select * from user where username like "%"#{name}"%";
</select>
在MyBatis核心配置文件中,配置日志,STDOUT_LOGGING为标准日志工厂
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
导入jar包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
配置log4j.properties文件
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
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/msg.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{yyyy-MM-dd HH:mm:ss}][%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
在MyBatis核心配置文件中,配置日志
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
导入相应的包:
import org.apache.log4j.Logger
创建对象:
Logger logger=Logger.getLogger(加载类.class)
日志级别
语法:
select * from 表名 limit 起始值,查询条数
Dao接口
List<User> getUserByLimit(Map<String,Integer> map);
Mapper.xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize};
</select>
测试
SqlSession sqlSession = MyBatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<>();
map.put("startIndex",0);
map.put("pageSize",5);
List<User> userList = mapper.getUserByLimit(map);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
Dao接口
List<User> getUserByRowBounds();
Mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
select * from user
</select>
测试
SqlSession sqlSession = MyBatisUtils.getSqlSession();
RowBounds rowBounds=new RowBounds(0,5);
List<User> userList = sqlSession.selectList("cn.demo.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
需要在MyBatis核心配置文件中绑定接口
<mappers>
<mapper class="cn.demo.dao.UserMapper"/>
</mappers>
注解在接口中的方法上实现
@Select("select * from user")
List<User> getUsers();
@Param()注解
安装插件
Maven导入坐标
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
在实体类上加注解:
<resultMap id="stuAndTea" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<!--关联对象property 关联对象在Student实体类中的属性-->
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
<select id="getStudent" resultMap="stuAndTea">
select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid=t.id;
</select>
<resultMap id="stuAndTea" type="Student">
<!--association关联属性 property属性名 column在多的一方的表中的列名 javaType属性类型 select查询语句-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getStudent" resultMap="stuAndTea">
select * from student;
</select>
<!--这里传递过来的id,只有一个属性的时候,下面可以写任何值association中column多参数配置:
column="{key=value,key=value}" 传递查询参数名称=字段名称
其实就是键值对的形式,key是传给下个sql的取值名称,value是sql查询的字段名。
-->
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{tid};
</select>
<resultMap id="teaAndStu" 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"/>
</collection>
</resultMap>
<select id="getTeacher" parameterType="int" resultMap="teaAndStu">
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>
<select id="getTeacher" parameterType="int" resultMap="teaAndStu">
select * from teacher where id=#{tid};
</select>
<resultMap id="teaAndStu" type="Teacher">
<collection property="students" column="id" javaType="ArrayList" ofType="Student" select="getStudents"/>
</resultMap>
<select id="getStudents" resultType="Student">
select * from student where tid=#{id};
</select>
if:提供了可选的查找文本功能,test条件内容为true才会执行,否者不执行
select * from blog
<where>
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
choose (when, otherwise)
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
1=1
</otherwise>
</choose>
</where>
trim (where, set)
<trim prefix="WHERE" prefixoverride="AND |OR">
prefix:前缀
prefixoverride:去掉第一个and或者是or
</trim>
<trim prefix="set" suffixoverride="," suffix=" where id = #{id} ">
prefix:前缀
suffixoverride:去掉最后一个逗号
suffix:后缀
</trim>
抽取SQL语句公共部分,方便复用
<sql id="指定ID名">
公共部分
</sql>
在需要重复的地方使用include标签引用
<include refid="ID名"/>
<foreach collection="" item="" open="" close="" separator="">
sql语句
</foreach>
一级缓存也叫本地缓存:
缓存失效的情况
查询不同的语句
增删改操作,改变原来的数据,必定会刷新缓存
手动清理
sqlSession.clearCache();
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
工作机制
步骤
序列化实体类
在核心配置文件中开启全局缓存(默认开启)
<setting name="cacheEnabled" value="true"/>
在Mapper.xml文件中开启二级缓存
<cache/>
可选参数:
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"
创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
导包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
Mapper.xml指定使用缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
编写ehcache.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径
-->
<diskStore path="./tmpdir/Tmp_EhCache"/>
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
</ehcache>