学习MyBatis必须先学懂JDBC、MySQL、Maven
复习跳转 :JDBC
MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。
➢MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
➢MyBatis 可以使用简单的XML或注解来配置和映射原生类型、接口和Java的POJO (Plain Old JavaObjects,普通老式Java对象)为数据库中的记录。
➢MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。
➢2013年11月迁移到Github。
核心作用:帮助程序员将数据存入到数据库中
方便(为了更好的偷懒)
传统的JDBC代码太复杂了,简化,框架,自动化
不用MyBatis也可以,只是更复杂,学了更容易上手。
优点(特性):
➢简单易学:本身就很小且简单。
➢灵活:不会对应用程序或数据库设的现有设计有任何影响。
➢解除了sql和代码的耦合或者说分离,提高了可维护性。
➢提供映射标签,支持对象与数据库的orm字段关系映射。
➢提供对象关系映射标签,支持对象关系组建维护。
➢提供xml标签,支持编写动态sql。
maven仓库:
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
数据持久化
➢持久化就是将程序的数据在持久状态和瞬时状态转化的过程
➢ 内存:断电即失
➢数据库(Jdbc),io文件持久化。
➢持久化生活案例:冷藏、罐头、真空压缩
有一些数据或对象,不能让他丢掉。
在生活中懂电脑的同学都知道 内存很贵。
Dao层、Service层、Controller层
完成持久化工作的代码块
层界限模块化很明显
为什么要学它?(因为方便,简单灵活,提高了代码的可维护性)
重要的一点:使用的人多,技多不压身!
a)mybatis 框架在分层架构中的一个定位?
b)Mybatis 框架的应用优势?(简单,灵活)
c)MyBatis 框架核心API?(SqlSession,SqlSessionFactory,SqlSessionFactoryBuilder,…)
d)MyBatis 框架API会话应用的执行过程?(SqlSession->DataSource-Connection-JDBCAPI-SQL)
e)MyBatis 中的动态SQL应用,参数表达式#{}?
f)MyBatis 中的常用配置?(映射文件路径,驼峰命名规则,事务超时时间。)
a)@Mapper注解的作用是什么?
b)DAO中方法参数为什么有时需要使用@Param注解描述?
c)什么情况下将sql映射写到dao方法上?(推荐简单sql)
d)SQL映射中什么请求下会使用resultType?(简单查询)
e)动态sql的语法结构是怎样的?(参考官网-https://mybatis.org/mybatis-3)
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`(`id `,`name`,`pwd`) VALUES
(1,'清风','123456'),
(2,'张三','123456'),
(3,'李四','456789')
<!--导入依赖-->
<dependencies>
<!--mysqlq驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
选中项目 --> New --> Module…
这种创建方式有一个好处:子模块不用在导包.
<?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核心配置文件-->
<configuration>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="JDBC" />
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的四个基本信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。
SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。
而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
package com.cy.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;
//SqlSessionFactory --> sqlSession
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory = null;
static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例.
// SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
package com.cy.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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
//get、set自己创建
}
以往我们写接口的方法(这种写法会写很多的JDBC语句) ,使用我们不在使用这种写法
MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
package com.cy.dao;
import com.cy.pojo.User;
import java.util.List;
/**以前的写法,这种写法会写很多的JDBC
*MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集。
* 所以这种方法不需要了,不建议写这种
* */
public class UserDaoImpl implements UserDao {
public List<User> getUserList(){
//执行SQL
select * from mybatis.user
//结果集 ResultSet
}
}
所以我们删除UserDaoImpl ,创建UserDao 类,使用xml映射
public interface UserDao {
public List<User> getUserList();
}
接口实现类 (由原来的UserDaoImpl转变为一个Mapper配置文件)
这里我们只需记住:
resultMap:字面意思:代表 集合
resultType:字面意思:代表 类型
<?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">
<!--namespace=绑定一个指定的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
<select id="getUserList" resultType="com.kuang.pojo.User"><!--resultType返回一个结果 List<User>-->
select * from USER
</select>
</mapper>
在test中创建一个测试类:
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
//第一步获得SqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行SQL(绑定接口)
//方式一:getMapper
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
//方式二:不建议使用
//List userList = sqlSession.selectlist("com.cy.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
运行:
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?(核心配置文件中注册mappers)
解决:
在mybatis-config.xml中配置注册文件
<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<!--每一个Mapper.XML都需要在Mybatis核心配置文件中注册!-->
<mappers>
<mapper resource="com/cy/dao/UserMapper.xml"/>
</mappers>
maven由于他的约定大于配置,所以我们写的配置文件,无法被导出或者生效
解决方案:
在pom中添加:(避免出现)
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
1.配置文件没有注册
2.绑定接口错误
3.方法名不对
4.返回类型不对
5.Maven导出资源问题
6.xml中不能写中文
7.空指针异常
8.mysql版本8.0和我的不一样
namespace中的包名要和Dao/Mapper接口的包名一致
选择,查询语句;
id:就是对应的namespace中的方法名;
resultType : Sql语句执行的返回值;
parameterType : 参数类型;
1.编写接口
package com.cy.dao;
import com.cy.pojo.User;
import java.util.List;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
}
2.编写对应的mapper中的sql语句
<?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="com.cy.dao.UserMapper">
<select id="getUserList" resultType="com.cy.pojo.User">
select * from mybatis.user
</select>
<select id="getUserById" parameterType="int" resultType="com.cy.pojo.User">
select * from mybatis.user where id = #{id}
</select>
</mapper>
3.测试
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user=mapper.getUserById(1);
System.out.println(user);
//关闭sqlSession
sqlSession.close();
}
1.编写接口
2.编写对应的mapper中的sql语句
<select id="getUserById" parameterType="int" resultType="com.cy.pojo.User">
select * from mybatis.user where id = #{id}
</select>
<!--对象中的属性,可以直接取出来-->
<insert id="addUser" parameterType="com.cy.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
3.测试
@Test
public void getUserById() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user=mapper.getUserById(1);
System.out.println(user);
//关闭sqlSession
sqlSession.close();
}
@Test
public void addUser() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int res = mapper.addUser(new User(4,"淡若清风","123456"));
if (res >0){
System.out.println("插入成功");
}
//增删改一定要提交事务
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
1.编写接口
package com.cy.dao;
import com.cy.pojo.User;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//insert一个用户
int addUser(User user);
//修改用户
int updateUser(User user);
}
2.编写对应的mapper中的sql语句
<update id="updateUser" parameterType="com.cy.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
3.测试
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(5,"CSND","123123"));
//增删改一定要提交事务
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
1.编写接口
package com.cy.dao;
import com.cy.pojo.User;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//insert一个用户
int addUser(User user);
//修改用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
}
2.编写对应的mapper中的sql语句
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id =#{id};
</delete>
3.测试
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(5);
//增删改一定要提交事务
sqlSession.commit();
//关闭sqlSession
sqlSession.close();
}
注意点:
增删改查需要提交事务!
1)标签不要匹配错
2)resource绑定mapper,需要使用路径!
3)程序配置文件必须符合规范!
4)NullPointerException,没有注册到资源!
5)输出的xml文件中存在中文乱码问题!
6)maven资源没有导出问题!
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应该考虑使用Map!
1.UserMapper接口
User getUserById2(Map<String,Object> map);
2.UserMapper.xml
<!--对象中的属性可以直接取出来 传递map的key-->
<insert id="addUser2" parameterType="map">
insert into user (id,name,password) values (#{userid},#{username},#{userpassword})
</insert>
3.测试
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("userid",5);
map.put("username","清风");
mapper.addUser2(map);
//关闭资源
sqlSession.close();
}
Map传递参数,直接在sql中取出key即可! 【parameter=“map”】
对象传递参数,直接在sql中取出对象的属性即可! 【parameter=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用Map , 或者注解!
1.Java代码执行的时候,传递通配符% _%
List<User> userList = mapper.getUserLike("%李%");
2.在sql拼接中使用通配符
select * from user where name like "%"#{value}"%"
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
去掉不要的部分
package com.cy.dao;
import com.cy.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
//查询全部用户
List<User> getUserList();
//根据ID查询用户
User getUserById(int id);
//insert一个用户
int addUser(User user);
//修改用户
int updateUser(User user);
//删除一个用户
int deleteUser(int id);
}
<?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核心配置文件-->
<configuration>
<!--配置环境-->
<environments default="test">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<transactionManager type="JDBC"/>
<!--配置数据源(连接池)-->
<dataSource type="POOLED">
<!--配置连接数据库的四个基本信息-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?userSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/cy/dao/UserMapper.xml"/>
</mappers>
</configuration>
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserDaoTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
}
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境
学会使用配置多套运行环境!
MyBatis默认的事务管理器就是JDBC ,连接池:POOLED
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。【application.properties】
编写一个配置文件
application.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=root
1.可以直接引入外部文件
<! --引入外部配置文件-->
<properties resource="application.properties">
<property name="username" value="root"/>
<property name="pwd" value="123456"/>
</properties>
2.可以在其中增加一些属性配置
3.如果两个文件有同一个字段,优先使用外部配置文件的
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置.
意在降低冗余的全限定类名书写。
<!--可以给实体类起别名-->
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包,每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为 author,;若有注解,则别名为其注解值。
见下面的例子:
<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>
在实体类比较少的时候,使用第一种方式。
如果实体类十分多,建议用第二种扫描包的方式。
第一种可以DIY别名,第二种不行,如果非要改,需要在实体上增加注解。
@Alias("author")
public class Author {
...
}
API参考官网:mybatis官网
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins 插件
1.mybatis-generator-core(原始工程(自动生成代码))
既然 MyBatis 的行为已经由上述元素配置完了,我们现在就要来定义 SQL 映射语句了。 但首先,我们需要告诉 MyBatis 到哪里去找到这些语句。 在自动查找资源方面,Java 并没有提供一个很好的解决方案,所以最好的办法是直接告诉 MyBatis 到哪里去找映射文件。 你可以使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等。例如:
MapperRegistry:注册绑定我们的Mapper文件;
方式一:【推荐使用】
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<mapper resource="com/cy/dao/UserMapper.xml"/>
</mappers>
方式二:使用class文件绑定注册
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册-->
<mappers>
<mapper class="com.cy.dao.UserMapper"/>
</mappers>
注意点:
接口和他的Mapper配置文件必须同名
接口和他的Mapper配置文件必须在同一个包下
方式三:使用包扫描进行注入:
<mappers>
<package name="com.cy.dao"/>
</mappers>
声明周期和作用域是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBuilder:
1)一旦创建了SqlSessionFactory,就不再需要它了
2)局部变量
SqlSessionFactory:
1)可以理解为:数据库连接池
2)SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建一个实例。
3)因此SqlSessionFactory的最佳作用域是应用作用域(ApplocationContext)。
4)最简单的就是使用单例模式或静态单例模式。
SqlSession:
1)连接到连接池的一个请求
2)SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
3)用完之后需要赶紧关闭,否则资源被占用!
这里面的每一个Mapper,就代表一个具体的业务!
1.问题一:
数据库中的字段
新建一个项目,拷贝之前的,测试实体类字段不一致的情况
修改实体类的pwd改为password
老样子清空不要的内容:
public interface UserMapper {
//根据ID查询用户
User getUserById(int id);
}
<?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="com.cy.dao.UserMapper">
<select id="getUserById" resultType="com.cy.pojo.User">
select * from mybatis.user where id = #{id}
</select>
</mapper>
创建测试类:
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
//关闭sqlSession
sqlSession.close();
}
}
<?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="com.cy.dao.UserMapper">
<select id="getUserById" resultType="com.cy.pojo.User">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
</mapper>
在xml配置
<!--给实体类起别名-->
<typeAliases>
<package name="com.cy.pojo"/>
</typeAliases>
怎么把pwd转换成password呢?
id name pwd
id name password
创建结果集映射
<?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="com.cy.dao.UserMapper">
<!--结果集映射-->
<!--id对应取的别名,type实体类类名-->
<resultMap id="UserMap" type="user">
<!-- column数据库中的字段,property实体类中的属性-->
<!--<result column="id" property="id"/>
<result column="name" property="name"/>-->
<!--哪里不同映射哪里-->
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
</mapper>
1)resultMap 元素是 MyBatis 中最重要最强大的元素。
2)ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
3)ResultMap 的优秀之处——你完全可以不用显式地配置它们。
4)如果这个世界总是这么简单就好了。
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的助手!
曾经:sout、debug
现在:日志工厂
SLF4J
LOG4J 【掌握】
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
STDOUT_LOGGING 【掌握】
NO_LOGGING
在MyBatis中具体使用哪一个日志实现,在设置中设定
配置:
在mybatis核心配置文件中,配置我们的日志!
一个字都不能错,一个多余的空格都不能有!
标准的日志工厂实现
<!--标准的日志工厂实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
什么是Log4j?
百度百科:Log4j详细解析
1)Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件;
2)我们也可以控制每一条日志的输出格式;
3)通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程;
4)最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
创建log4j配置文件
#将等级为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/rzp.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.sq1.PreparedStatement=DEBUG
<settings>
<setting name="logImpl" value="Log4j"/>
</settings>
1.在要使用Log4j的类中,导入包 import org.apache.log4j.Logger;
2.日志对象,参数为当前类的class对象
Logger logger = Logger.getLogger(UserDaoTest.class);
3.测试
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
//日志对象,参数为当前类的class对象
Logger logger = Logger.getLogger(UserDaoTest.class);
@Test
public void getUserLike() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
logger.info("info: 进入getUserLike方法成功!");
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
//关闭sqlSession
sqlSession.close();
}
@Test
public void testLog4j(){
logger.info("info: 进入了testLog4j方法");
logger.debug("debug:进入了testLog4j");
logger.error("error:进入了testLog4j");
}
}
3.日志级别
logger.info("info: 测试log4j");
logger.debug("debug: 测试log4j");
logger.error("error:测试log4j");
为什么分页?(减少数据的处理量)
◆ 每页显示2个,从0页开始查
SELECT * from user limit 0,2
◆ 从0开始,3页开始查,
SELECT * from user limit 3
package com.cy.dao;
import com.cy.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
//根据ID查询用户
User getUserById(int id);
//分页
List<User> getUserByLimit(Map<String,Integer> map);
}
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from user limit #{startIndex},#{pageSize}
select>
@Test
public void getUserByLimit() {
//获取sqlSession
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startIndex", 0);//从0开始
map.put("pageSize", 2);//显示2位
List<User> list = mapper.getUserByLimit(map);
for (User user : list) {
System.out.println(user);
}
}
不再使用SQL实现分页
1.接口
//RowBounds分页
List<User> getUserByRowBounds();
2.mapper.xml
<!--RowBounds分页-->
<select id="getUserByRowBounds" resultMap="UserMap">
select * from user
</select>
3.测试
@Test
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//RowBounds实现
RowBounds rowBounds = new RowBounds(1, 2);
//通过Java代码层面实现分页
List<User> userList = sqlSession.selectList("com.cy.dao.UserMapper.getUserByRowBounds", null, rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
大家之前都学过面向对象编程,也学习过接口,但在真正的开发中,很多时候我们会选择面向接口编程。
◆ 根本原因∶解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变得容易,规范性更好。
◆ 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;
◆ 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
◆ 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
◆ 接口的本身反映了系统设计人员对系统的抽象理解。
◆ 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
◆ 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface) ;
一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
◆ 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法.
◆ 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现.
◆ 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题.更多的体现就是对系统整体的架构
接口类
package com.cy.dao;
public interface UserMapper {
}
实体类
public class User {
private int id;
private String name;
private String password;
public User() {}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
//自己导入get、set、toString
}
工具类
package com.cy.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;
//SqlSessionFactory --> sqlSession
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory = null;
static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
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();
}
}
application.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=root
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核心配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="application.properties"/>
<!--标准的日志工厂实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<package name="com.cy.pojo"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<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>
</configuration>
准备工作完成
package com.cy.dao;
import com.cy.pojo.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
}
<mappers>
<mapper class="com.cy.dao.UserMapper"/>
</mappers>
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlsession = MybatisUtils.getSqlSession();
//底层主要应用反射
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
List<User> users = mapper.getUsers();
for (User user : users) {
System.out.println(user);
}
sqlsession.close();
}
}
我们可以发现我的所有配置文件都被注入到了sqlSession里面,它会去读取。
通过反射我们可以拿到全类名,以及它的全部属性。
把SqlSession 设置为true
一旦设置为true 以后的所有东西都不用手动
◆ 修改工具类
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
◆ 修改接口
//方法存在多个参数,所有的参数前面必须加上@Param(" ")注解
@Select("select * from user where id=#{id}")
User getUserByID(@Param("id")int id,@Param("name")String name);
◆ 测试
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
@Test
public void test(){
SqlSession sqlsession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
User userById = mapper.getUserByID(1,"清风");
System.out.println(userById);
sqlsession.close();
}
}
◆ 接口
@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);
◆ 测试
@Test
public void insert(){
SqlSession sqlsession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
mapper.addUser(new User(5,"李刚","123123"));
sqlsession.close();
}
◆ 接口
@Update({"update user set name=#{name}.pwd=#{password} where id=#{id}"})
int updateUser(User user);
◆ 测试
@Test
public void update(){
SqlSession sqlsession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
mapper.updateUser(new User(5,"马云","123123"));
sqlsession.close();
}
◆ 接口
@Delete( "delete from user where id = #{id}")
int deleteUser(@Param("id") int id);
◆ 测试
@Test
public void detele(){
SqlSession sqlsession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlsession.getMapper(UserMapper.class);
mapper.deleteUser(5);
sqlsession.close();
}
我们必须要将接口绑定到我们的核心配置文件中!
使用Class文件绑定接口注册
<mappers>
<mapper class="com.cy.dao.UserMapper"/>
mappers>
注意点:
◆ 接口和他的Mapper配置文件必须同名!
◆ 接口和他的Mapper配置文件必须在同一个包下!
关于@Param( )注解
◆ 基本类型的参数或者String类型,需要加上
◆ 引用类型不需要加
◆ 如果只有一个基本类型的话,可以忽略,但是建议大家都加上
◆ 我们在SQL中引用的就是我们这里的@Param()中设定的属性名
◆ #{} 和 ${}的区别:
${} 注入什么就是什么,且如果是简单类型的值需要用 value 来接收
#{} 将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号
#方式能够很大程度防止sql注入;$方式无法防止Sql注入。
$方式一般用于传入数据库对象,例如传入表名。
一般能用#的就别用$ 。MyBatis排序时使用order by 动态参数时需要注意,用$而不是#。
Lombok是一款Java开发插件,使得Java开发者可以通过其定义的一些注解来消除业务工程中冗长和繁琐的代码,尤其对于简单的Java模型对象(POJO)。在开发环境中使用Lombok插件后,Java开发人员可以节省出重复构建,诸如hashCode和equals这样的方法以及各种业务对象模型的accessor和ToString等方法的大量时间。对于这些方法,它能够在编译源代码期间自动帮我们生成这些方法,并没有如反射那样降低程序的性能。
想要体验—把Lombok的话,得先在自己的开发环境中安装上对应的插件。
在使用lombok注解的时候记得要导入lombok.jar包到工程
如果使用的是Maven的工程项目的话,要在其pom.xml中添加依赖如下:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
这是我们之前的实体类
package com.cy.pojo;
/**实体类*/
public class User {
private int id;
private String name;
private String password;
public User() {
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
我们使用Lombok优化
package com.cy.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**实体类*/
@Data //无参构造,get、set、tostring、hashcode,equals
@NoArgsConstructor //无参构造
@AllArgsConstructor //有参构造
public class User {
private int id;
private String name;
private String password;
}
@Data //无参构造,get、set、tostring、hashcode,equals
@NoArgsConstructor //无参构造
@AllArgsConstructor //有参构造
@ToString //toString方法
@EqualsAndHashCode //HashCode
@Getter //放在类上生成所有get方法,放在字段 只生成当前单独的get方法
1.能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率
2.让代码变得简洁,不用过多的去关注相应的方法
3.属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等
1.不支持多种参数构造器的重载
2.虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度
Lombok虽然有很多优点,但Lombok更类似于一种IDE插件,项目也需要依赖相应的jar包。Lombok依赖jar包是因为编译时要用它的注解,为什么说它又类似插件?因为在使用时,eclipse或Intelli IDEA都需要安装相应的插件,在编译器编译时通过操作AST(抽象语法树)改变字节码生成,变向的就是说它在改变java语法。
它不像spring的依赖注入或者mybatis的ORM一样是运行时的特性,而是编译时的特性。这里我个人最感觉不爽的地方就是对插件的依赖!因为Lombok只是省去了一些人工生成代码的麻烦,但IDE都有快捷键来协助生成getter/setter等方法,也非常方便。
知乎上有位大神发表过对Lombok的一些看法:
这是一种低级趣味的插件,不建议使用。5AVa发展到今天,各种插件层出不穷,如何甄别各种插件的优劣?能从架构上优化你的设计的,能提高应用程序性能的,实现高度封装可扩展的…,像l ombrok这种,像这种插件,已经不仅仅是插件了,改变了你如何编写源码,事实上,少去了的代码,你写上去又如何?如果JAVA家族到处充斥这样的东西,那只不过是一坨披着金属颜色的屎,迟早会被其它的语言取代。
虽然话糙但理确实不糙,试想一个项目有非常多类似Lombok这样的插件,个人觉得真的会极大的降低阅读源代码的舒适度。虽然非常不建议在属性的getter/setter写一些业务代码,但在多年项目的实战中,有时通过给getter/setter加一点点业务代码,能极大的简化某些业务场景的代码。所谓取舍,也许就是这时的舍弃一定的规范,取得极大的方便。
我现在非常坚信一条理念,任何编程语言或插件,都仅仅只是工具而已,即使工具再强大也在于用的人,就如同小米加步枪照样能嬴飞机大炮的道理一样。结合具体业务场景和项目实际情况,无需一味追求高大上的技术,适合的才是王道。
Lombok有它的得天独厚的优点,也有它避之不及的缺点,熟知其优缺点,在实战中灵活运用才是王道。
1.导入lombok
2.新建实体类Teacher,Student
3.建立Mapper接口
4.建立Mapper.xml文件
5.在核心配置文件中绑定注册我们的Mapper接口或者文件 【方式很多,随心选】
6.测试查询是否能够成功
◆ 多个学生,对应一个老师
◆ 对于学生这边而言,关联,多个学生,关联一个老师【多对一】
◆ 对于老师而言,集合,一个老师,有很多学生【一对多】
CREATE TABLE `teacher` (
`id`INT (10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY( `id`),
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `teacher` (`id`, `name`) VALUES ('1', '清风老师');
CREATE TABLE `student` (
`id`INT (10) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`tid` INT(10) DEFAULT NULL,
PRIMARY KEY( `id`),
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');
)
项目下载:
链接:https://pan.baidu.com/s/1erHaT_avxIKlhRGMb-qlfA
提取码:b3qb
工具类
package com.cy.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;
//SqlSessionFactory --> sqlSession
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory = null;
static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
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();
}
}
Student 类
package com.cy.pojo;
public class Student {
private int id;
private String name;
//学生需要关联一个老师!
private Teacher teacher;
}
Teacher 类
package com.cy.pojo;
import lombok.Data;
@Data
public class Teacher {
private int id;
private String name;
}
StudentMapper 接口
package com.cy.dao;
public interface StudentMapper {
}
TeacherMapper 接口
package com.cy.dao;
import com.cy.pojo.Teacher;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface TeacherMapper {
@Select("select * from teacher where id = #{tid}")
Teacher getTeacher(@Param("tid") int id);
}
配置数据库连接
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=root
配置环境
<?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核心配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="application.properties"/>
<!--标准的日志工厂实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<package name="com.cy.pojo"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<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 class="com.cy.dao.TeacherMapper"/>
<mapper class="com.cy.dao.StudentMapper"/>
</mappers>
</configuration>
package com.cy.dao;
import com.cy.pojo.Teacher;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
public class MyTest {
public static void main(String[] args) {
SqlSession sqlSession= MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
}
分析sql查询语句
select s.id,s.name,t.name from student s,teacher t where s.tid =t.id;
修改接口
package com.cy.dao;
import com.cy.pojo.Student;
import java.util.List;
public interface StudentMapper {
//查询所有的学生信息,以及对应的老师的信息!
public List<Student> getStudent();
}
配置StudentMapper.xml
<mapper namespace="com.cy.dao.StudentMapper">
<select id="getStudent" resultType="Student">
select * from student;
</select>
</mapper>
测试:
@Test
public void testStudent(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<Student> studentList = mapper.getStudent();
for (Student student:studentList){
System.out.println(student);
}
sqlSession.close();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
思路:
1. 查询所有的学生信息
2. 根据查询出来的学生的tid寻找特定的老师 (子查询)
-->
<mapper namespace="com.cy.dao.StudentMapper">
<!--先查学生-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student;
</select>
<!--单独处理学生中老师的字段-->
<resultMap id="StudentTeacher" type="Stuent">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独出来
对象:association /关联(association)
集合:collection
-->
<collection property="teacher" column="tid" javaType="teacher" select="getTeacher"/>
</resultMap>
<!--在查老师-->
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
</mapper>
property:映射到列结果的字段或属性
column:数据库中的列名或者列的别名
javaType:一个java类的完全限定名,或一个类型别名。
jdbcType:JDBC类型
resultMap:结果映射的 ID,可以将嵌套的结果集映射到一个合适的对象树中。
<!--按照结果集查询-->
<select id="getStudent2" resultMap="StudentTeacher2">
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="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="id" column="tid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
</association>
</resultMap>
第一种可以理解为:查出老师和学生,通过子查询 查老师
第二种可以理解为: 先查出学生的所有值,对于具体的tname,再去teacher里面查
回顾Mysql多对一查询方式:
◆ 子查询 (按照查询嵌套)
◆ 联表查询 (按照结果嵌套)
一个老师多个学生;
对于老师而言,就是一对多的关系;
新建一个项目或者把刚刚写的内容清理和开始的模板项目一样
这里就省略环境搭建了,和上面一样,把写的查询删除就可以了
修改实体类
package com.cy.pojo;
import lombok.Data;
import java.util.List;
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
package com.cy.pojo;
import lombok.Data;
@Data
public class Student {
private int id;
private String name;
private int teacher;
}
接口
public interface TeacherMapper {
Teacher getTeacher(@Param("tid") int id);
}
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s ,teacher t
where s.tid = t.id and t.id =#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理 对象:association 集合:collection
javaType=""指定属性的类型!
集合中的泛型信息,我们使用ofType获取
-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
测试:
@Test
public void test(){
SqlSession sqlSession= MybatisUtils.getSqlSession();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
Teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}
<!--=================================================-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id =#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid = #{tid}
</select>
1.关联 - association 【多对一】
2.集合 - collection 【一对多】
3.javaType & ofType
◆ JavaType用来指定实体类中的类型
◆ ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
◆ 保证SQL的可读性,尽量保证通俗易懂
◆ 注意一对多和多对一,属性名和字段的问题
◆ 如果问题不好排查错误,可以使用日志,建议使用Log4j
◆ Mysql引擎
◆ InnoDB底层原理
◆ 索引
◆ 索引优化
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
所谓的动态SQL,本质上还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
动态 SQL 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。
利用动态 SQL,可以彻底摆脱这种痛苦。
动态SQL元素和STL或基于类似XML的文本处理器相似。在MyBatis之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis采用功能强大的基于OGNL的表达式来淘汰具它大部分无素。
if
choose (when,otherwise)
trim (where,set)
foreach
CREATE TABLE `blog` (
`id` varchar(50) NOT NULL COMMENT '博客id',
`title` varchar(100) NOT NULL COMMENT '博客标题',
`author` varchar(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量',
)ENGINE=INNODB DEFAULT CHARSET=utf8
1.导包
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2.编写配置文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=root
<?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核心配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="application.properties"/>
<!--标准的日志工厂实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!--是否开启自动驼峰命名规则(camel case)映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<package name="com.cy.pojo"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<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 class="com.cy.dao.BlogMapper"/>
</mappers>
</configuration>
package com.cy.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;
//SqlSessionFactory --> sqlSession
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory = null;
static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
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(true);
}
}
package com.cy.utils;
import org.junit.Test;
import java.util.UUID;
//用UID方法生成随机的ID
@SuppressWarnings("all")//预制警告(让警告不显示)
public class IDutils {
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-"," ");
}
//测试
@Test
public void test(){
System.out.println(IDutils.getID());
}
}
3.编写实体类
import lombok.Data;
import java.util.Date;
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;//属性名和字段名不一致
private int views;
}
4.编写实体类对应Mapper接口和Mapper.xml文件
package com.cy.dao;
public interface BlogMapper {
//插入数据
int addBlog(Blog blog);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog (id, title,author,create_time,views)
values (#{id},#{title}, #{author}, #{createTime}, #{views})
</insert>
</mapper>
创建一个测试类:
插入数据
public class MyTest {
@Test
public void addInitBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog=new Blog();
blog.setId(IDutils.getID());
blog.setTitle("Mybatis");
blog.setAuthor("淡若清风");
blog.setCreateTime(new Date());
blog.setViews(9999);
mapper.addBlog(blog);
blog.setId(IDutils.getID());
blog.setTitle("JAVA");
mapper.addBlog(blog);
blog.setId(IDutils.getID());
blog.setTitle("Spring5");
mapper.addBlog(blog);
blog.setId(IDutils.getID());
blog.setTitle("微服务");
mapper.addBlog(blog);
}
}
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。比如:
<select id="findActiveBlogWithTitleLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
</select>
这条语句提供了可选的查找文本功能。如果不传入 “title”,那么所有处于 “ACTIVE” 状态的 BLOG 都会返回;如果传入了 “title” 参数,那么就会对 “title” 一列进行模糊查找并返回对应的 BLOG 结果(细心的读者可能会发现,“title” 的参数值需要包含查找掩码或通配符字符)。
如果希望通过 “title” 和 “author” 两个参数进行可选搜索该怎么办呢?首先,我想先将语句名称修改成更名副其实的名称;接下来,只需要加入另一个条件即可。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
看完概述开始编写:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.dao.BlogMapper">
<insert id="addBlog" parameterType="blog">
insert into blog(id, title, author, create_time, views)
values (#{id},#{title},#{author},#{createTime},#{views});
</insert>
<select id="queryBlogIF" parameterType="map" resultType="blog">
<!--1=1是为了where后所有判断条件都不符合时,依然可以执行查询而不报错-->
select * from blog where 1=1
<!--判断是否为空,不为空就执行拼接-->
<!--sql语句: select * from blog where 1=1 and title ="java"-->
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author =#{author}
</if>
</select>
</mapper>
package com.cy.dao;
import com.cy.pojo.Blog;
import java.util.List;
import java.util.Map;
public interface BlogMapper {
//插入数据
int addBlog(Blog blog);
//查询博客
List<Blog> queryBlogIF(Map map);
}
测试:
@Test
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.queryBlogIF(map);
for (Blog blog:blogs){
System.out.println(blog);
}
sqlSession.close();
}
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
前面几个例子已经方便地解决了一个臭名昭著的动态 SQL 问题。现在回到之前的 “if” 示例,这次我们将 “state = ‘ACTIVE’” 设置成动态条件,看看会发生什么。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
WHERE
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</select>
如果没有匹配的条件会怎么样?最终这条 SQL 会变成这样:
SELECT * FROM BLOG
WHERE
这会导致查询失败。如果匹配的只是第二个条件又会怎样?这条 SQL 会是这样:
SELECT * FROM BLOG
WHERE
AND title like ‘someTitle’
这个查询也会失败。这个问题不能简单地用条件元素来解决。这个问题是如此的难以解决,以至于解决过的人不会再想碰到这种问题。
MyBatis 有一个简单且适合大多数场景的解决办法。而在其他场景中,可以对其进行自定义以符合需求。而这,只需要一处简单的改动:
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG
<where>
<if test="state != null">
state = #{state}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null and author.name != null">
AND author_name like #{author.name}
</if>
</where>
</select>
where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
接口
//查询博客Choose
List<Blog> queryBlogChoose(Map map);
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
title=#{title}
when>
<when test="author != null">
and author= #{author}
when>
<otherwise>
and views =#{views}
otherwise>
choose>
where>
select>
测试:
@Test
public void queryBlogChoose(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
// map.put("title", "java");
map.put("author", "淡若清风");
map.put("views", 9999);
List<Blog> blogs=mapper.queryBlogChoose(map);
for (Blog blog:blogs){
System.out.println(blog);
}
sqlSession.close();
}
接口
//更新博客
int updateBlog(Map map);
<update id="updateBlog" parameterType="map">
update blog
<set><!--和where差不多,set是发现 ,就给你去掉-->
<if test="title !=null">
title = #{title},
</if>
<if test="author != null">
author=#{author}
</if>
</set>
where id= #{id}
</update>
测试:
@Test
public void updateBlog(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("title", "java2");
map.put("author", "淡若清风2");
map.put("id", "80ae0f8e fd78 41bf bc9e 97ec174aee46");
//map.put("views", 9999);
mapper.updateBlog(map);
sqlSession.close();
}
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
◆ 最好基于单标来定义SQL片段
◆ 不要存在where标签
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
◆ 先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可。
有的时候,我们可能会将一些功能的部分抽取出来,方便复用!
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author =#{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
◆ 最好基于单标来定义SQL片段
◆ 不要存在where标签
参考:
//select * from user where 1=1 and (id=1 or id=2 or id=3)
select * from user where 1=1 and
<foreach item="id" in collection="ids"
open="(" separator="or" close=")">
</foreach>
查询第1-2-3号记录的博客
接口
//查询第1-2-3号记录的博客
List<Blog> queryBlogForeach(Map map);
<!--
select * from user where 1=1 and (id=1 or id=2 or id=3)
我们现在传递一个map,这个map中可以存一个集合
-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--collection="ids"集合 item="id"从集合中遍历出来每一项的名字为id
遍历:
open=""以什么开始,close=""关闭,separator=""分隔符
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id= #{id}
</foreach>
</where>
</select>
测试:
@Test
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids", ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog b1og : blogs) {
System.out.println(b1og);
}
sqlSession.close();
}
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
建议:
◆ 先在Mysql中写出完整的SQL,再对应的去修改成我们的动态SQL实现通用即可
查询 : 连接数据库,耗资源
◆ 一次查询的结果,给他暂存一个可以直接取到的地方 --> 内存:缓存
我们再次查询的相同数据的时候,直接走缓存,不走数据库了
◆ 存在内存中的临时数据
◆ 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题
◆ 减少和数据库的交互次数,减少系统开销,提高系统效率
◆ 经常查询或不经常改变的数据 【可以使用缓存】
◆ MyBatis包含- - 个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率。
◆ MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
• 默认情况下,只有一 -级缓存开启。 (SqlSession级别的缓存, 也称为本地缓存)
• 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
• 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。
一级缓存也叫本地缓存:SqlSession
与数据库同一次会话期间查询到的数据会放在本地缓存中
以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库
新建一个mybatis-08项目
配置环境:
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核心配置文件-->
<configuration>
<!--引入外部配置文件-->
<properties resource="application.properties"/>
<!--标准的日志工厂实现-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--给实体类起别名-->
<typeAliases>
<package name="com.cy.pojo"/>
</typeAliases>
<!--配置环境-->
<environments default="mysql">
<!--配置mysql环境-->
<environment id="mysql">
<!--配置事务的类型-->
<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 class="com.cy.dao.UserMapper"/>
</mappers>
</configuration>
application.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username=root
password=root
pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties
**/ *.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
工具类
package com.cy.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;
//SqlSessionFactory --> sqlSession
public class MybatisUtils {
static SqlSessionFactory sqlSessionFactory = null;
static {
try {
//使用Mybatis第一步 :获取sqlSessionFactory对象
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(true);
}
}
创建一个实体类
package com.cy.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
创建接口和xml
UserMapper
public interface UserMapper {
//根据id查询用户
User queryUserById(@Param("id") int id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.dao.UserMapper">
<select id="queryUserById" resultType="user">
select * from user where id = #{id}
</select>
</mapper>
测试:
package com.cy.dao;
import com.cy.pojo.User;
import com.cy.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class MyTest {
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
User user2 = mapper.queryUserById(1);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
}
1.开启日志!
2.测试在一个Sesion中查询两次相同记录
3.查看日志输出
1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
User user2 = mapper.queryUserById(2);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
我们在中间加一条语句,继续测试生效情况
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
public interface UserMapper {
//根据id查询用户
User queryUserById(@Param("id") int id);
int updateUser(User user);
}
<update id="updateUser" parameterType="user">
update user set name=#{name}, pwd=#{pwd} where id = #{id};
update>
测试:
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
mapper.updateUser(new User(2,"aaaa","bbbbb"));
User user2 = mapper.queryUserById(2);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
我们可以发现,增删改查操作可能会改变原来的数据,所以必定会刷新缓存!
3.查询不同的Mapper.xml
4.手动清理缓存
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.queryUserById(1);
System.out.println(user);
sqlSession.clearCache();//手动清理缓存
User user2 = mapper.queryUserById(2);
System.out.println(user2);
System.out.println(user==user2);
sqlSession.close();
}
一级缓存默认是开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段!
一缓存相当于就是一个map。
◆ 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
◆ 基于namespace级别的缓存,一个名称空间,对应一个二级缓存
工作机制
◆ 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
◆ 如果会话关闭了,这个会员对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
◆ 新的会话查询信息,就可以从二级缓存中获取内容
◆ 不同的mapper查询出的数据会放在自己对应的缓存(map)中
一级缓存开启(SqlSession级别的缓存,也称为本地缓存)
◆ 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
◆ 为了提高可扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存。
<!--显示的开启全局缓存-->
<setting name="cacheEnabled" value="true"/>
<!--在当前Mapper.xml中使用二级缓存-->
<cache/>
<!--在查询语句中也能使用二级缓存控制-->
<select id="queryUserById" resultType="user" useCache="true">
select * from user where id = #{id}
</select>
<!--在当前Mapper.xml中使用二级缓存-->
<!--readOnly为True时是读相同实例, false时是读拷贝值,相对安全,所以会出现比较时出现false
-->
<!--
eviction="FIFO" 使用FIFO输出策略
flushInterval="60000" 每隔60秒刷新缓存
size="512" 最多只能存512个缓存
readOnly="true" 是否只读
-->
<cache eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
◆ 问题:我们需要将实体类序列化,否则就会报错
◆ 只要开启了二级缓存,在同一个Mapper下就有效
◆ 所有的数据都会放在一级缓存中
◆ 只有当前会话提交,或者关闭的时候,才会提交到二级缓存中
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
1.要在程序中使用,需要导包:
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
2.在mapper中指定使用我们的ehcache缓存实现
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
Ehcache 中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 path="java.io.tmpdir"/>
<!--默认缓存设置-->
<defaultCache maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="true"
maxElementsOnDisk="10000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="FIFO"
/>
<!--
<cache name 缓存名唯一标识
maxElementsInMemory="1000" 内存中最大缓存对象数
eternal="false" 是否永久缓存
timeToIdleSeconds="3600" 缓存清除时间 默认是0 即永不过期
timeToLiveSeconds="0" 缓存存活时间 默认是0 即永不过期
overflowToDisk="true" 缓存对象达到最大数后,将其写入硬盘
maxElementsOnDisk="10000" 磁盘最大缓存数
diskPersistent="false" 磁盘持久化
diskExpiryThreadIntervalSeconds="120" 磁盘缓存的清理线程运行间隔
memoryStoreEvictionPolicy="FIFO" 缓存清空策略
FIFO 先进先出
LFU less frequently used 最少使用
LRU least recently used 最近最少使用
/>
-->
<cache name="testCache"
maxEntriesLocalHeap="2000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true"
memoryStoreEvictionPolicy="FIFO">
</cache>
</ehcache>
使用方法:
用法
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import java.net.URL;
public class EhcacheUtil {
private static final String default_path = "/ehcache.xml";
private URL url;
private CacheManager manager;
public CacheManager getManager() {
return manager;
}
public void setManager(CacheManager manager) {
this.manager = manager;
}
private EhcacheUtil() {
url = getClass().getResource(default_path);
manager = CacheManager.create(url);
manager.addCacheIfAbsent("default_cache");
}
private EhcacheUtil(String path) {
url = getClass().getResource(path);
System.out.println(url.getPath());
manager = CacheManager.create(url);
manager.addCacheIfAbsent("default_cache");
}
public void put(String cacheName, String key, Object value) {
Cache cache = manager.getCache(cacheName);
Element element = new Element(key, value);
cache.put(element);
}
public Object get(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
Element element = cache.get(key);
return element == null ? null : element.getObjectValue();
}
public Cache get(String cacheName) {
return manager.getCache(cacheName);
}
public void remove(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
cache.remove(key);
}
public static void main(String[] args){
EhcacheUtil ehcacheUtil = new EhcacheUtil("/ehcache.xml");
ehcacheUtil.put("default_cache","key","value");
String result = (String)ehcacheUtil.get("default_cache","key");
System.out.println(result);
//System.out.println(EhcacheUtil.class.getResource(""));
}
}