本文图文学习教程
学自b站狂神:狂神说–Mybatis篇
如何获取Mybais:
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
中文文档:https://mybatis.org/mybatis-3/zh/index.html
Github源码:https://github.com/mybatis/mybatis-3/releases
数据持久化:
为什么需要持久化:
Dao层、Service层、Controller层…
帮助程序猿更加方便的将存入到数据库中
传统的JDBC代码太复杂了。
框架更加简化,更加自动化,易上手。
使用人群多。
优点:
思路:搭建环境–>导入Mybatis–>编写代码–>测试
搭建数据库:
CREATE DATABASE `mybatis`;
Use `mybatis`;
create table `user`(
`id` INT(20) NOT NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT into user VALUES(1,"刘一手","123");
INSERT into user VALUES(2,"刘二手","123"),(3,"刘三手","123"),(4,"刘四手","123");
INSERT into user(id,name) VALUES(5,"刘五手");
新建项目
新建一个普通的maven项目,注:固定Maven路径
删除src目录,将项目作为父工程
导入maven依赖
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.lxfgroupId>
<artifactId>20200604-Mybatis-studyartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
dependencies>
project>
连接数据库错误解决:https://blog.csdn.net/ITMan2017/article/details/100601438
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="xxxx"/>
dataSource>
environment>
environments>
<mappers>
<mapper resource="com/lxf/dao/UserMapper.xml">mapper>
mappers>
configuration>
package com.lxf.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.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步:获取sqlSessionFactory对象
InputStream inputStream = MybatisUtils.class.getResourceAsStream("/mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
// public static void main(String[] args) {
// System.out.println(sqlSessionFactory);
// }
//既然有了SqlSessionFactory,就可以从中获取SqlSession的实例了。
//SqlSession 完全包含了面向数据库执行SQL命令所需的所有方法。
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
package com.lxf.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
package com.lxf.dao;
import com.lxf.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserDao {
//查询所有的User
List<User> getUserList();
//查询单独一个User
User getUser(int id);
}
<mapper namespace="com.lxf.dao.UserDao">
<select id="getUserList" resultType="com.lxf.pojo.User">
select * from mybatis.user;
select>
mapper>
出错点:
1.org.apache.ibatis.binding.BindingException:Type interface com.lxf.dao.UserDao is not konwn to the MapperRegistry
:每一个Mapper.xml没有在Mybatis核心配置文件中注册!
2.路径正确但是Mapper.xml文件资源无法找到:因为maven项目约定大于配置,资源只会在resource文件夹下搜索,pom.xml文件加上以下配置就可以解决错误:
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
测试类(Junit):
package com.lxf.dao;
import com.lxf.pojo.User;
import com.lxf.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class UserDaoTest {
@Test
public void test(){
SqlSession sqlSession =null;
try{
//1.获取session
sqlSession=MybatisUtils.getSqlSession();
//2.执行SQL
//方式一(推荐):
UserDao userDao = sqlSession.getMapper(UserDao.class);
System.out.println("userDao.getUserList() = " + userDao.getUserList());
//方式二:
User user = sqlSession.selectOne("getUser", 1);
System.out.println("user = " + user);
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭sqlSession
sqlSession.close();
}
}
}
1.修改UserMapper接口:
package com.lxf.dao;
import com.lxf.pojo.User;
import java.util.List;
public interface UserMapper {
//方式一:
//查询所有的User,配置在mapper.xml文件中
List<User> getUserList();
//查询单独一个User,注解不需要配置xml文件
User getUserById(int id);
//增加一个用户
int addUser(User user);
//增加多个用户
int addUsers(List<User> users);
//修改一个用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
}
2.修改mapper.xml文件:
<mapper namespace="com.lxf.dao.UserMapper">
<select id="getUserList" resultType="com.lxf.pojo.User">
select * from mybatis.user;
select>
<select id="getUserById" resultType="com.lxf.pojo.User" parameterType="int">
select * from mybatis.user where id=#{id};
select>
<insert id="addUser" parameterType="com.lxf.pojo.User">
insert into mybatis.user values(#{id},#{name},#{pwd});
insert>
<update id="updateUser" parameterType="com.lxf.pojo.User" >
update User as u set u.pwd=#{pwd},u.name=#{name} where u.id=#{id};
update>
<insert id="addUsers" parameterType="java.util.List" useGeneratedKeys="true">
INSERT INTO User (id,name,pwd)
VALUES
<foreach collection="list" separator="," item="item">
(#{item.id,jdbcType=INTEGER},
#{item.name,jdbcType=VARCHAR},
#{item.pwd,jdbcType=VARCHAR})
foreach>
insert>
<delete id="deleteUser" parameterType="int">
delete from User where id=#{id};
delete>
mapper>
3.编写测试类:
package com.lxf.dao;
import com.lxf.pojo.User;
import com.lxf.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlSession =null;
try{
//1.获取session
sqlSession=MybatisUtils.getSqlSession();
//2.执行SQL
//方式一(推荐):
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
System.out.println("userDao.getUserList() = " + userMapper.getUserList());
//方式二:
//User user = sqlSession.selectOne("getUser", 1);
//System.out.println("user = " + user);
} catch (Exception e) {
e.printStackTrace();
}finally {
//关闭sqlSession
sqlSession.close();
}
}
@Test
public void getUserById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//根据id查询一个用户
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// User user = mapper.getUserById(1);
// System.out.println("user = " + user);
//增加一个用户
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// int i=mapper.addUser(new User(9,"刘德华","234"));
// if(i>0){
// System.out.println("插入多条数据成功");
// }
//增加多个用户
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList=new ArrayList<User>();
userList.add(new User(10,"张学友","zxy"));
userList.add(new User(11,"周润发","zrf"));
userList.add(new User(12,"周星驰","zxc"));
int i = mapper.addUsers(userList);
if (i>0){
System.out.println("插入多条数据成功");
}
//修改一个用户
//UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//mapper.updateUser(new User(8,"刘八手","888"));
//删除指定的一个用户
// UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// mapper.deleteUser(8);
//提交事务
sqlSession.commit();
sqlSession.close();
}
}
注意点:
增删改需要提交事务
在增加多个数据时,url要加上:&allowMultiQueries=true
mapper文件中如果错用标签会发生截然不同的事情,例如:在select标签下sql用增加语句,会导致查询后返回为null,且不需要提交事务。原因:select标签下也可以用其他的查询语句,但select标签默认返回值为null,且不需要提交事务。
如果我们的实体类含有大量字段,但是在插入、修改的时候不需要全部填写,就可以用这种方法省时省力
UserMapper接口:
//增加一个用户,万能Map方式
int addUser2(Map<String,Object> map);
UserMapper.xml配置文件
<insert id="addUser2">
insert into mybatis.user(id,name) values(#{userId},#{userName});
insert>
测试类:
@Test
public void addUser2(){
//获取session对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//获取UserMapper对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map=new HashMap<String,Object>();
map.put("userId",14);
map.put("userName","王小法");
//执行方法
int i=userMapper.addUser2(map);
if(i>0){
System.out.println("插入成功!");
}
sqlSession.commit();
sqlSession.close();
}
1.传统挺配符:% %
List<User> usersLike = userMapper.getUsersLike("%周%");
2.在sql拼接中使用通配符
select * from user where name like "%"#{value}"%";
3.注意
标签中注释的sql也会编译,所以不用的sql就要删了,注释没用,会报错,一般就是参数数量不匹配。
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)(需要再了解)
objectFactory(对象工厂)(需要再了解)
plugins(插件)(需要再了解)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)(需要再了解)
mappers(映射器)(需要再了解)
<environments default="test">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx"/>
dataSource>
environment>
<environment id="test">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx"/>
dataSource>
environment>
environments>
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【db.properties】
编写配置文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
username=xxx
password=xxx
mybatis-config.xml文件配置:
<properties resource="db.properties"/>
<!-直接配置:可以增加,或者全部配置-->
<!-若外部配置文件与这里重复,优先外部-->
<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>
常见错误:
1.直接指定一个类,然后给他起别名(可以DIY别名)
Mybatis.xml文件:
<typeAliases>
<typeAlias type="com.lxf.pojo.User" alias="User"/>
typeAliases>
UserMapper.xml:
<select id="getUserById" resultType="User" parameterType="int">
select * from mybatis.user where id=#{id};
select>
2.也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean。
扫描实体类的包,它的默认别名就为这个类的类名,首字母小写。就例如扫描com.lxf.pojo,pojo下有两个类:User、Student
那么他们两个的包路径别名分别为user、student(包名多的时候非常有用,默认是类名首字母小写).
如要DIY类名:在这个包下的类上加上注解:@Alias(“xxx”)
Mybatis.xml文件:
<typeAliases>
<package name="com.lxf.pojo"/>
typeAliases>
UserMapper.xml:
<select id="getUserById" resultType="User" parameterType="int">
select * from mybatis.user where id=#{id};
select>
MapperRegistry:注册绑定我们的Mapper文件;
方式一【推荐使用】:
<mappers>
<mapper resource="com/lxf/dao/UserMapper.xml">mapper>
mappers>
方式二:使用class文件绑定注册
<mappers>
<mapper class="com.lxf.dao.UserMapper"/>
mappers>
注意点:
接口和他的Mapper配置文件必须同名!
接口和他的Mapper配置文件必须在同一个包下!
方式三:使用扫描包进行注入
<mappers>
<package name="com.lxf.dao"/>
mappers>
注意点:
接口和他的Mapper配置文件必须同名!
接口和他的Mapper配置文件必须在同一个包下!
生命周期和作用域,是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactory
SqlSessionFactory:
SqlSession
数据库的字段:
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
测试问题:查出来的字段password为null(数据库不为null)
select * from mybatis.user where id=#{id};
类型处理器
select id,name,pwd from mybatis.user where id=#{id};
解决方法:
起别名
select id,name,pwd as password from mybatis.user where id=#{id};
resultMap
结果集映射
resultMap
元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets
数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。实际上,在为一些比如连接的复杂语句编写映射代码的时候,一份 resultMap
能够代替实现同等功能的数千行代码。ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
id name pwd
id name password
UserMapper.xml文件配置:
<select id="getUserById" resultMap="UserMap" parameterType="int">
select * from mybatis.user where id=#{id};
select>
<resultMap id="UserMap" type="user">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
resultMap>
如果一个数据库操作,出现了异常,我们需要排错。
日志可以打印清晰的日志信息,方便我们查询错误信息、sql信息、步骤信息等
曾经:sout、debug。现在:日志
在Mybatis具体使用哪一日志,在设置中设定!
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
settings>
注意:logImpl大小写要注意,名字和值都不能多出空格
(1)、先导入log4j的包
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
(2)、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/lxf.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
3.配置log4j为日志的实现
<settings>
<setting name="logImpl" value="LOG4J"/>
settings>
4.log4j的使用
"C:\Program Files\Java\jdk1.8.0_161\bin\java.exe" -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.4\lib\idea_rt.jar=65112:C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.4\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.4\lib\idea_rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.4\plugins\junit\lib\junit5-rt.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2019.3.4\plugins\junit\lib\junit-rt.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_161\jre\lib\rt.jar;C:\Users\dell\IdeaProjects\20200604-Mybatis-study\mybatis-03\target\test-classes;C:\Users\dell\IdeaProjects\20200604-Mybatis-study\mybatis-03\target\classes;E:\maven\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar;E:\maven\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;E:\maven\repository\org\mybatis\mybatis\3.5.2\mybatis-3.5.2.jar;E:\maven\repository\junit\junit\4.12\junit-4.12.jar;E:\maven\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.lxf.dao.UserMapperTest,test
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.logging.LogFactory]-Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.datasource.pooled.PooledDataSource]-PooledDataSource forcefully closed/removed all connections.
[org.apache.ibatis.io.VFS]-Class not found: org.jboss.vfs.VFS
[org.apache.ibatis.io.JBoss6VFS]-JBoss 6 VFS API is not available in this environment.
[org.apache.ibatis.io.VFS]-Class not found: org.jboss.vfs.VirtualFile
[org.apache.ibatis.io.VFS]-VFS implementation org.apache.ibatis.io.JBoss6VFS is not valid in this environment.
[org.apache.ibatis.io.VFS]-Using VFS adapter org.apache.ibatis.io.DefaultVFS
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/test-classes/com/lxf/dao
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/test-classes/com/lxf/dao
[org.apache.ibatis.io.DefaultVFS]-Reader entry: UserMapperTest.class
[org.apache.ibatis.io.DefaultVFS]-Listing file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/test-classes/com/lxf/dao
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/test-classes/com/lxf/dao/UserMapperTest.class
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/test-classes/com/lxf/dao/UserMapperTest.class
[org.apache.ibatis.io.DefaultVFS]-Reader entry: ���� 4 W
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao
[org.apache.ibatis.io.DefaultVFS]-Reader entry: UserMapper.class
[org.apache.ibatis.io.DefaultVFS]-Reader entry: UserMapper.xml
[org.apache.ibatis.io.DefaultVFS]-Listing file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao/UserMapper.class
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao/UserMapper.class
[org.apache.ibatis.io.DefaultVFS]-Reader entry: ���� 4 getUserById (I)Lcom/lxf/pojo/User;
[org.apache.ibatis.io.DefaultVFS]-Find JAR URL: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao/UserMapper.xml
[org.apache.ibatis.io.DefaultVFS]-Not a JAR: file:/C:/Users/dell/IdeaProjects/20200604-Mybatis-study/mybatis-03/target/classes/com/lxf/dao/UserMapper.xml
[org.apache.ibatis.io.DefaultVFS]-Reader entry:
[org.apache.ibatis.io.ResolverUtil]-Checking to see if class com.lxf.dao.UserMapperTest matches criteria [is assignable to Object]
[org.apache.ibatis.io.ResolverUtil]-Checking to see if class com.lxf.dao.UserMapper matches criteria [is assignable to Object]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Opening JDBC Connection
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Created connection 1095293768.
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4148db48]
[com.lxf.dao.UserMapper.getUserById]-==> Preparing: select * from mybatis.user where id=?;
[com.lxf.dao.UserMapper.getUserById]-==> Parameters: 1(Integer)
[com.lxf.dao.UserMapper.getUserById]-<== Total: 1
user = User{id=1, name='刘一手', password='123'}
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@4148db48]
[org.apache.ibatis.transaction.jdbc.JdbcTransaction]-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@4148db48]
[org.apache.ibatis.datasource.pooled.PooledDataSource]-Returned connection 1095293768 to pool.
Process finished with exit code 0
4.简单使用
private static Logger logger=Logger.getLogger(UserMapperTest.class);
@Test
public void logTest(){
logger.info("成功进入");
logger.debug("debug信息");
logger.error("错误信息");
}
[com.lxf.dao.UserMapperTest]-成功进入
[com.lxf.dao.UserMapperTest]-debug信息
[com.lxf.dao.UserMapperTest]-错误信息
为什么分页:减少数据的处理量
select * from user limit startIndex,pageSize;
select * from user limit 0,2;
使用Mybatis实现分页,核心SQL
//分页查询
List<User> getUserBylimit(Map<String,Integer> map);
<select id="getUserBylimit" resultMap="userMap" parameterType="map">
select * from user limit #{startIndex},#{pageSize};
select>
@Test
public void getUserByLimit(){
//获取SqlSession对象
SqlSession session = MybatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
Map<String,Integer> map=new HashMap<String,Integer>();
//给map添加键值对
map.put("startIndex",1);
map.put("pageSize",2);
//执行方法
List<User> userBylimit = mapper.getUserBylimit(map);
for (User user : userBylimit) {
System.out.println("user = " + user);
}
//关闭session
session.close();
}
UserMapper.java接口:
//分页查询2
List<User> getUserByRoundBounds();
UserMapper.xml配置文件:
<select id="getUserByRoundBounds" resultMap="userMap">
select * from user;
select>
测试类:
@Test
public void getUserByRowBounds(){
//获取SqlSession对象
SqlSession session = MybatisUtil.getSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1, 3);
List<User> users = session.selectList("com.lxf.dao.UserMapper.getUserByRoundBounds", null, rowBounds);
for (User user : users) {
System.out.println("user = " + user);
}
//关闭session
session.close();
}
@Select(value = "select * from user")
List<User> getUsers();
<mappers>
<mapper class="com.lxf.dao.UserMapper"/>
mappers>
3.测试(和之前的Mapper方法一样)
运行过程拓展:
1.UserMapper.java接口类
package com.lxf.dao;
import com.lxf.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface UserMapper {
@Select(value = "select * from user")
List<User> getUsers();
//方法存在多个参数,必须每个参数前面必须加上@Param注解
@Select(value = "select * from user where id =#{id}")
User getUserById(int id2);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set id=#{id},name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id=#{id2}")
int deleteUser(@Param("id2") int id);
}
2.测试类
import com.lxf.dao.UserMapper;
import com.lxf.pojo.User;
import com.lxf.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
//查询一个数据
@Test
public void test(){
SqlSession session = MybatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
// List users = mapper.getUsers();
//
// for (User user : users) {
// System.out.println("user = " + user);
// }
User user = mapper.getUserById(1);
System.out.println("user = " + user);
session.close();
}
//增加一个数据
@Test
public void test2(){
SqlSession session = MybatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.addUser(new User(15,"成龙","cl"));
if(i>0){
System.out.println("插入成功!");
}
session.close();
}
//更新一个数据
@Test
public void test3(){
SqlSession session = MybatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.updateUser(new User(14,"刘小法","lxf"));
if(i>0){
System.out.println("更新成功!");
}
session.close();
}
//删除一个用户
@Test
public void test4(){
SqlSession session = MybatisUtil.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int i = mapper.deleteUser(5);
if(i>0){
System.out.println("删除成功!");
}
session.close();
}
}
3.注意:
//返回selsession,并设置自动提交为true
return sqlSessionFactory.openSession(true);
@Delete("delete from user where id=#{id2}")
int deleteUser(@Param("id2") int id);
<mappers>
<mapper class="com.lxf.dao.UserMapper"/>
mappers>
SQl数据库建立对应的表:
CREATE TABLE `teacher`(
`id` INT(10) not NULL PRIMARY KEY,
`name` VARCHAR(30) DEFAULT NULL
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO teacher(id,name) VALUES(1,'刘老师');
create table `student`(
`id` INT(10) not null PRIMARY KEY,
`name` VARCHAR(30) DEFAULT null,
`tid` INT(10) DEFAULT null,
KEY `fktid` (`tid`),
CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO student(id,name,tid) VALUES(1,'小明',1);
INSERT INTO student(id,name,tid) VALUES(2,'小红',1);
INSERT INTO student(id,name,tid) VALUES(3,'小张',1);
INSERT INTO student(id,name,tid) VALUES(4,'小李',1);
INSERT INTO student(id,name,tid) VALUES(5,'小王',1);
Student类:
package com.lxf.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
//学生需要关联一个老师!
private Teacher teacher;
}
Teacher类
package com.lxf.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
}
StudentMapper.java接口
package com.lxf.dao;
import com.lxf.pojo.Student;
import java.util.List;
public interface StudentMapper {
//查询所有的学生信息,以及对应的老师的信息!
List<Student> getStudents();
}
StudentMapper.xml文件:
<mapper namespace="com.lxf.dao.StudentMapper">
<select id="getStudents" resultMap="studentMap" >
select * from student
select>
<resultMap id="studentMap" type="Student">
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
resultMap>
<select id="getTeacher" resultType="com.lxf.pojo.Teacher">
select * from teacher where id=#{id};
select>
mapper>
测试类:
@Test
public void getStudents(){
SqlSession sqlSession = MybatisUtil.getSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = studentMapper.getStudents();
for (Student student: students) {
System.out.println("student = " + student);
}
sqlSession.close();
}
StudentMapper.java接口类:
//查询所有的学生信息,以及对应的老师的信息!
List<Student> getStudents2();
StudentMapper.xml配置文件:
<select id="getStudents2" resultMap="studentMap2">
select s.id sid,s.name sname,t.name tname from student s,teacher t where s.tid=t.id;
select>
<resultMap id="studentMap2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher" >
<result property="id" column="sid"/>
<result property="name" column="tname"/>
association>
resultMap>
测试类:
@Test
public void getStudents2(){
SqlSession sqlSession = MybatisUtil.getSession();
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = studentMapper.getStudents2();
for (Student student: students) {
System.out.println("student = " + student);
}
sqlSession.close();
}
比如:一个老师拥有多个学生!对于老师而言就是一对多的关系
1.环境搭建,和第8点一样
Student实体类:
package com.lxf.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
//学生需要关联一个老师!
private int tid;
}
Teacher实体类:
package com.lxf.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
private int id;
private String name;
//一个学生拥有多个学生
private List<Student> students;
}
TeacherMapper.java接口类:
//获取这个老师及其所有的学生
Teacher getTeachers2(@Param("tid") int id);
TeacherMapper.java配置文件:
<select id="getTeachers2" resultMap="teacherMap2" >
select * from mybatis.teacher where id=#{tid};
select>
<resultMap id="teacherMap2" type="com.lxf.pojo.Teacher">
<result column="id" property="id"/>
<result column="name" property="name"/>
<collection property="students" column="id" javaType="ArrayList" ofType="com.lxf.pojo.Student" select="getStudentByTeacherId"/>
resultMap>
<select id="getStudentByTeacherId" resultType="com.lxf.pojo.Student">
select * from mybatis.student where tid=#{tid};
select>
测试类:
@Test
public void getTeachers2(){
SqlSession sqlSession = MybatisUtil.getSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeachers2(1);
System.out.println("teacher = " + teacher);
sqlSession.close();
}
TeacherMapper.java接口类:
//获取这个老师及其所有的学生
Teacher getTeachers3(@Param("tid") int id);
TeacherMapper.java配置文件:
<select id="getTeachers3" resultMap="teacherMap3">
select t.id tid,t.name tname,s.id sid,s.name sname,s.tid stid from teacher t,student s where t.id=#{tid} and s.tid=#{tid};
select>
<resultMap id="teacherMap3" type="com.lxf.pojo.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="com.lxf.pojo.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="stid"/>
collection>
resultMap>
测试类:
@Test
public void getTeachers3(){
SqlSession sqlSession = MybatisUtil.getSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeachers3(1);
System.out.println("teacher = " + teacher);
sqlSession.close();
}
关联-association【多对一】
集合-collection【一对多】
javaType & ofType
注意点:
什么是动态sql:动态SQL就是根据不同的条件生成不同的SQL语句
如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。
sql语句:
create table `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` VARCHAR(30) NOT NULL COMMENT '创建时间',
`views` INT(30) not null COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建一个基础工程
BlogMapper.java接口文件:
//插入数据
int addBlog(Blog blog);
BlogMapper.xml配置文件:
<insert id="addBlog" parameterType="com.lxf.pojo.Blog">
insert into mybatis.blog(id,title,author,create_time,views) values (#{id},#{title},#{author},#{createTime},#{views});
insert>
测试类
@Test
public void addBlog(){
SqlSession sqlSession = MybatisUtil.getSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
int i = mapper.addBlog(new Blog(IDUtils.getID(), "Mybatis学习方法", "刘一手", new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()), 1060));
int j = mapper.addBlog(new Blog(IDUtils.getID(), "SpringMVC学习方法", "刘二手", new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()), 530));
int k = mapper.addBlog(new Blog(IDUtils.getID(), "Spring5学习方法", "刘三手", new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()), 777));
int l = mapper.addBlog(new Blog(IDUtils.getID(), "SSM学习方法", "刘四手", new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()), 666));
if(i>0&&j>0&&k>0&&l>0){
System.out.println("成功插入四条数据!");
}
sqlSession.close();
}
BlogMapper.java接口类
//查询博客
List<Blog> queryBlogIF(Map map);
BlogMapper.xml配置文件:
<select id="queryBlogIF" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from mybatis.blog where 1=1
<if test="title !=null">
and title=#{title}
if>
<if test="author !=null">
or author=#{author}
if>
select>
测试类:
@Test
public void queryBlogIF(){
SqlSession sqlSession = MybatisUtil.getSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map=new HashMap();
map.put("title","Mybatis学习方法");
map.put("author","刘四手");
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println("blog = " + blog);
}
sqlSession.close();
}
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回views大于多少的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员挑选的 Blog)。
BlogMapper.java接口类:
//查询博客
List<Blog> queryBlogChoose(Map map);
BlogMapper.xml配置文件:
<select id="queryBlogChoose" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title !=null">
title=#{title}
when>
<when test="author !=null">
author=#{author}
when>
<otherwise>
views > #{views}
otherwise>
choose>
where>
select>
测试类:
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtil.getSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map=new HashMap();
map.put("title","Mybatis学习方法");
map.put("author","刘四手");
map.put("views",666);
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println("blog = " + blog);
}
sqlSession.close();
}
思考:如果没有where 1=1这个条件该怎么查?以下有解决方法:
<select id="queryBlogIF" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from mybatis.blog where
<if test="title !=null">
title=#{title}
if>
<if test="author !=null">
or author=#{author}
if>
select>
如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:
SELECT * FROM BLOG
WHERE
这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:
SELECT * FROM BLOG
WHERE
or author=#{author}
这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。
MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:
<select id="queryBlogIF" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from mybatis.blog
<where>
<if test="title !=null">
title=#{title}
if>
<if test="author !=null">
or author=#{author}
if>
where>
select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列,它会检测,是否多余,多余则会自动去掉,比如下面最后views参数没传递就会造成,多余。
BlogMapper.java接口类:
//更新数据
int updateBlogSet(Map map);
BlogMapper.xml配置文件:
<update id="updateBlogSet" parameterType="map" >
update blog
<set>
<if test="title !=null">
title=#{title},
if>
<if test="author !=null">
author=#{author},
if>
<if test="views !=null">
views=#{views}
if>
set>
where id=#{id}
update>
测试类:
@Test
public void updateBlogSet(){
SqlSession sqlSession = MybatisUtil.getSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map=new HashMap();
map.put("title","Mybatis学习简便方法");
map.put("author","刘五手");
//map.put("views",690);
map.put("id","72bae714f52f4cf196e194114cb35b1f");
int i = mapper.updateBlogSet(map);
if(i>0){
System.out.println("更新数据成功");
}
sqlSession.close();
}
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<select id="queryBlogIF" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from mybatis.blog
<trim prefix="WHERE" prefixOverrides="AND |OR ">
<if test="title !=null">
title=#{title}
if>
<if test="author !=null">
or author=#{author}
if>
trim>
select>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
update blog
title=#{title},
author=#{author},
views=#{views}
where id=#{id}
注意,我们覆盖了后缀值设置,并且自定义了前缀值。一般上面两种用where和set就可以了,如果mybatis没有的建议再用trim
举例(查询一些指定id的Blog):
BlogMapper.java接口类:
//查询第多个记录的博客
List<Blog> queryBlogForeach(Map map);
BlogMapper.xml配置文件:
<select id="queryBlogForeach" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from blog
<where>
/*
collection:要循环的list名字
open:开始语句
separator:每个循环后添加的分隔符(除最后一次)
close:结束语句
item:list中每个数据
index:list的下标
*/
<foreach collection="ids" separator="," open="id in (" close=")" item="item">
#{item}
foreach>
where>
select>
测试类:
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtil.getSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map=new HashMap();
List list=new ArrayList();
list.add("4");
list.add("3");
list.add("1");
map.put("ids",list);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println("blog = " + blog);
}
sqlSession.close();
}
<sql id="if-title-authorOR">
<if test="title !=null">
title=#{title}
if>
<if test="author !=null">
or author=#{author}
if>
sql>
<select id="queryBlogIF" parameterType="map" resultType="com.lxf.pojo.Blog">
select * from mybatis.blog
<where>
<include refid="if-title-authorOR">include>
where>
select>
bind
元素允许你在 OGNL 表达式以外创建一个变量,并将其绑定到当前的上下文。比如:
<select id="selectBlogsLike" resultType="Blog">
<bind name="pattern" value="'%' + _parameter.getTitle() + '%'" />
SELECT * FROM BLOG
WHERE title LIKE #{pattern}
select>
如果配置了 databaseIdProvider,你就可以在动态代码中使用名为 “_databaseId” 的变量来为不同的数据库构建特定的语句。比如下面的例子:
<insert id="insert">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
<if test="_databaseId == 'oracle'">
select seq_users.nextval from dual
if>
<if test="_databaseId == 'db2'">
select nextval for seq_users from sysibm.sysdummy1"
if>
selectKey>
insert into users values (#{id}, #{name})
insert>
查询:连接数据库,耗资源!
一次查询的结果,给他暂存到一个可以直接取得地方!–>内存;缓存
我们再次查询相同得数据时,直接走缓存,就不用走数据库了
存在内存中的临时数据。
将用户经常查询到的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询的效率,解决了高并发系统的性能问题
一级缓存也叫本地缓存
缓存失效的情况:
步骤:
<setting name="cacheEnabled" value="true"/>
UserMapper.java接口类:
//查询所有的User
List<User> getUsers();
UserMapper.xml配置文件
<select id="getUsers" resultType="com.lxf.pojo.User">
select * from user;
select>
<cache eviction="FIFO" flushInterval="600000" size="500" />
测试类:
@Test
public void getUsers(){
SqlSession sqlSession1 = MybatisUtil.getSession();
SqlSession sqlSession2 = MybatisUtil.getSession();
UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
List<User> users1 = mapper1.getUsers();
for (User user : users1) {
System.out.println("user = " + user);
}
sqlSession1.close();
System.out.println("==========================================");
UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
List<User> users2 = mapper2.getUsers();
for (User user : users2) {
System.out.println("user = " + user);
}
sqlSession2.close();
}
问题:未将实体类序列化而报错。解决方法:实体类继承serializable接口就可以了
Ehache是一种广泛使用的开源Java分布缓存,主要面向通用缓存
导依赖
<dependency>
<groupId>org.mybatis.cachesgroupId>
<artifactId>mybatis-ehcacheartifactId>
<version>1.2.1version>
depenency>
UserMapper.xml配置:
<!--eh缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache" />
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<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"/>
ehcache>