Mybatis
MyBatis(前身是iBatis)是一个支持普通SQL查询、存储过程以及高级映射的持久层框架。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集,它可以使用简单的XML或注解来配置和映射SQL信息,将接口和JAVA的POJO映射成数据库中的记录。
ORM框架
对象-关系映射(OBJECT/RELATIONALMAPPING,简称ORM),是随着面向对象的软件开发方法发展而产生的。用来把对象模型表示的对象映射到基于SQL的关系模型数据库结构中去。这样,我们在具体的操作实体对象的时候,就不需要再去和复杂的SQL语句打交道,只需简单的操作实体对象的属性和方法
Hibernate与MyBatis有什么区别?
Hibernate
Hibernate是一个全表映射的框架。
通常开发者只需定义好持久化对象到数据库表的映射关系,就可以通过Hibernate提供的方法完成持久层操作。
开发者并不需要熟练的掌握SQL语句的编写,Hibernate会根据制定的存储逻辑,自动的生成对应的SQL,并调用JDBC接口来执行,所以其开发效率会高于MyBatis。
Hibernate也存在一些缺点,例如它在多表关联时,对SQL查询的支持较差;更新数据时,需要发送所有字段;不支持存储过程;不能通过优化SQL来优化性能等。
MyBatis
MyBatis是一个半自动映射的框架。
“半自动”是相对于Hibernate全表映射而言的,MyBatis需要手动匹配提供POJO、SQL和映射关系,而Hibernate只需提供POJO和映射关系即可。
与Hibernate相比,虽然使用MyBatis手动编写SQL要比使用Hibernate的工作量大,但MyBatis可以配置动态SQL并优化SQL,可以通过配置决定SQL的映射规则,它还支持存储过程等。对于一些复杂的和需要优化性能的项目来说,显然使用MyBatis更加合适。
MyBatis的工作原理
1:首先读取配置文件,之后加载配置文件
2:通过构造SessionFactory 创建SqlSession回话
3:使用SqlSession对象操作数据库
4:关闭SqlSession
Mapper.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace表示命名空间 -->
<mapper namespace="com.mapper.CustomerMapper">
<!--根据客户编号获取客户信息 -->
<select id="findCustomerById" parameterType="Integer"
resultType="com.po.Customer">
select * from t_customer where id = #{id}
</select>
<!--根据客户名模糊查询客户信息列表-->
<select id="findCustomerByName" parameterType="String"
resultType="com.po.Customer">
<!-- select * from t_customer where username like '%${value}%' -->
select * from t_customer where username like concat('%',#{value},'%')
</select>
<!-- 添加客户信息 -->
<insert id="addCustomer" parameterType="com.po.Customer">
insert into t_customer(username,jobs,phone)
values(#{username},#{jobs},#{phone})
</insert>
<!-- 更新客户信息 -->
<update id="updateCustomer" parameterType="com.po.Customer">
update t_customer set
username=#{username},jobs=#{jobs},phone=#{phone}
where id=#{id}
</update>
<!-- 删除客户信息 -->
<delete id="deleteCustomer" parameterType="Integer">
delete from t_customer where id=#{id}
</delete>
</mapper>
myBatis.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>
<!--1.配置环境 ,默认的环境id为mysql-->
<environments default="mysql">
<!--1.2.配置id为mysql的数据库环境 -->
<environment id="mysql">
<!-- 使用JDBC的事务管理 -->
<transactionManager type="JDBC" />
<!--数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<!--2.配置Mapper的位置 -->
<mappers>
<mapper resource="com/mapper/CustomerMapper.xml" />
</mappers>
</configuration>
SqlSessionFactory介绍
SqlSessionFactory是MyBatis框架中十分重要的对象,它是单个数据库映射关系经过编译后的内存镜像,其主要作用是创建SqlSession。
SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来构建,而SqlSessionFactoryBuilder则可以通过XML配置文件或一个预先定义好的Configuration实例构建出SqlSessionFactory的实例
SqlSessionFactory获取
InputStream inputStream = Resources.getResourceAsStream("配置文件位置");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSessionFactory对象是线程安全的,它一旦被创建,在整个应用执行期间都会存在。如果我们多次的创建同一个数据库的SqlSessionFactory,
那么此数据库的资源将很容易被耗尽。为此,通常每一个数据库都会只对应一个SqlSessionFactory,所以在构建SqlSessionFactory实例时,建议使用单列模式。
什么是SqlSession
SqlSession是MyBatis框架中另一个重要的对象,它是应用程序与持久层之间执行交互操作的一个单线程对象,其主要作用是执行持久化操作。
使用完SqlSession对象后要及时关闭,通常可以将其放在finally块中关闭
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
// 此处执行持久化操作
} finally {
sqlSession.close();
}
获取SqlSession
String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2、根据配置文件构建SqlSessionFactory
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
// 3、通过SqlSessionFactory创建SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
SqlSession方法
selectOne 方法
T selectOne(String statement, Object parameter);
Customer customer = sqlSession.selectOne("com.mapper.CustomerMapper.findCustomerById", 1);
selectLis方法
List<E> selectList(String statement);
List<E> selectList(String statement, Object parameter);
List<Customer> customers = sqlSession.selectList("com.mapper.CustomerMapper.findCustomerByName", "j");
insert方法
int insert(String statement);
int insert(String statement, Object parameter);
int rows = sqlSession.insert("com.mapper.CustomerMapper.addCustomer", customer);
update方法
int update(String statement);
int update(String statement,int update(String statement););
int rows = sqlSession.update("com..mapper.CustomerMapper.updateCustomer", customer);
delete方法
int delete(String statement);
int delete(String statement, Object parameter);
int rows = sqlSession.delete("com.mapper.CustomerMapper.deleteCustomer", 4);
其他方法:
void commit(); 提交事务的方法。
void rollback(); 回滚事务的方法。
void close(); 关闭SqlSession对象。
<T> T getMapper(Class<T> type); 返回Mapper接口的代理对象。
Connection getConnection(); 获取JDBC数据库连接对象的方法
SqlSession获取工具类
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
Mybaties缓存
MyBatis 提供查询缓存,如果缓存中有数据就不用从数据中获取,用于减轻数据压力,提高系统性能,MyBatis的查询缓存总共有两级
一级缓存是SqlSession级别的缓存,在操作数据库时需要构造sqlsession对象,在对象中有一个数据结构(hashMap)用于存储缓存数据
不同的sqlSession之间的缓存数据区域(HashMap)是互相不影响的
二级缓存是MApper(namespace级别的缓存) 多个sqlsession去操作同一个mapper的sql语句,多个sqlsession可以共用
二级缓存 二级缓存是跨sqlsession的