持久层框架
工具和框架
工具:
JDBC -> DbUtils(QueyRunner) -> JdbcTemplate:
功能简单,SQL语句编写在Java代码中,这是硬编码,高耦合。
框架:
框架是整体解决方案。
如何进行事务控制,如何实现查询缓存。框架考虑的就很多。
Jdbc工具
Hibernate
全自动全映射Orm(Object Relation Mapping) 框架,旨在消除Sql,只要告诉它javaBean和对应的数据库中的表,就可以完成映射,但是这样也有他自己的问题,不能优化Sql,无法定制Sql
我们希望sql语句能够交给开发人员来编写,我们还希望Sql不失去灵活性。
Mybatis
Sql与java代码分离,SQL是开发人员控制,只需要掌握好Sql就行了。
Mysql是一个半自动的轻量级的Orm框架
Mybatis开发步骤
基本开发步骤
1、引入Mybatis开发依赖jar包,和mysql数据库驱动包
2、创建Mybatis核心配置文件
3、创建MybatisSQL文件,并将SQL文件注册到核心配置文件中
4、根据Mybatis核心配置文件创建SqlSessionFactory对象
5、Mysql通过SqlSessionFactory.openSession()来获取SqlSession对象
6、Mysql通过sqlSession.selectOne(“命名空间.唯一标识”, 参数);执行SQL并接收处理数据库的返回值。
Mybatis开发实例
1、基本开发实例
(1)添加maven依赖
(2)编写Mybatis核心配置文件
(3)编写SQL文件
(4)整合SQL文件和核心配置文件
(5)创建SqlSessionFactory对象
(6)获取SqlSession对象,SqlSession.method(namespace.id,param)
(7)释放资源
2、函数式接口
(1)添加maven依赖
(2)编写Mybatis核心配置文件
(3)编写SQL文件
(4)整合SQL文件和核心配置文件
(5)创建SqlSessionFactory对象
(6)获取SqlSession对象,SqlSession.getMapper( 编写Mapper接口,通过全限定类名.方法名 绑定 Mapper.xml文件,param)
(7)释放资源
公共部分:
(1)(2)(3)(4)
基本开发实例
- 依赖文件
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion><groupId>com.dashu</groupId><artifactId>mybatis</artifactId><version>V1.0.1</version><dependencies><!--引入druid数据源--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.8</version></dependency><!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.37</version></dependency><!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.1</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>compile</scope></dependency></dependencies>
</project>
- 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.dashu.mybatis.EmployeeMapper"><!--id:唯一标识resultType:返回值类型#{id}:从传递过来的参数中取出id值。这个参数就是id--><select id="selectEmp" resultType="com.dashu.bean.Employee">select id,last_name lastName,gender,email from tbl_employee where id = #{id}</select>
</mapper>
- 核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><!--在类路径下直接写配置文件名--><!--将我们写好的Mapper文件注册到核心配置文件当中--><mapper resource="EmployeeMapper.xml"/></mappers>
</configuration>
package com.dashu.application;import com.dashu.bean.Employee;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;/*** @Auther: DaShu* @Date: 2021/7/22 21:56* @Description:*/
public class MybatisTest {@Testpublic void testOne() throws IOException {//创建SqlSessionFactory对象,String path = "mybatis-config.xml";//全局配置文件。InputStream resourceAsStream = Resources.getResourceAsStream(path);SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);//获取SqlSession实例,能执行已经映射的SQL语句。SqlSession sqlSession = sessionFactory.openSession();try {//第一个参数:明名空间+idEmployee employee = sqlSession.selectOne("com.dashu.mybatis.EmployeeMapper.selectEmp", 1);System.out.println(employee.toString());//Employee{id=1, lastName='null', email='tom@guigu.com', gender='0'}/*** 为什么last_name没有值?* 因为这个字段和数据库中字段不一致,所以不知道赋值给谁,所以就是null;* 解决办法:* (1)起别名。* 解决之后:* (1)Employee{id=1, lastName='tom', email='tom@guigu.com', gender='0'}* */}finally {sqlSession.close();//释放资源}}
}
接口式编程
- 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.dashu.mapper.EmployeeMapper"><!--id:唯一标识resultType:返回值类型#{id}:从传递过来的参数中取出id值。这个参数就是id--><select id="getEmpById" resultType="com.dashu.bean.Employee">select id,last_name lastName,gender,email from tbl_employee where id = #{id}</select>
</mapper>
- 函数式接口
package com.dashu.mapper;import com.dashu.bean.Employee;
import org.apache.ibatis.annotations.Mapper;/*** @Auther: DaShu* @Date: 2021/7/23 18:46* @Description:*/
@Mapper
public interface EmployeeMapper {public Employee getEmpById(Integer id);
}
- 实现逻辑
public SqlSessionFactory getSqlSessionFactory() throws IOException {//获取SqlsessionFactory对象;String path = "mybatis-config.xml";//全局配置文件。InputStream resourceAsStream = Resources.getResourceAsStream(path);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);return sqlSessionFactory;}@Testpublic void testTwo() throws IOException {SqlSession sqlSession = null;try {//获取SqlSessionFactory对象SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();//获取SessionFactory对象sqlSession = sqlSessionFactory.openSession();//获取接口的实现类对象,调用接口的方法。EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);Employee employee = mapper.getEmpById(1);System.out.println(employee);} catch (IOException e) {e.printStackTrace();sqlSession.close();}}
- 函数式接口总结
1、函数式接口的函数中Mybatis会为接口创建实现类对象,这是一种代理对象,方法的真正的执行者是代理对象。
2、函数式接口的编写方式是使用的最多的,我们使用这个也是最多的。
3、SqlSession代表和数据库的一次会话,使用这个SqlSession的原生Api还是使用getMapper,这个对象都代表和数据库的一次会话,用完必须关闭,里边有一个getConnection()方法
4、SqlSession和Connection对象一样,都是非线程安全的,非线程安全的话不能把他编写成成员变量,这样的话多线程条件下,不能公用,每次使用都应该获取新的对象。
5、Mapper接口没有实现类,Mybatis会为这个接口生成一个代理对象,这个sqlSession.getMapper(Employee.class)返回的是接口的代理对象,这个代理对象一定是把xml文件和接口绑定起来了的对象。
6、两个重要的配置文件,Mybatis全局配置文件,包含数据库连接池信息,事务管理器信息等系统运行环境,SQL映射文件,这个是必须要有的,里边有每一个SQL语句映射信息,在这个文件中每一个SQL语句,唯一标识和返回的结果和参数都会在SQL语句 中有体现,Mybatis就是通过这类映射文件将SQL抽取出来访问数据库。
Mybatis核心配置文件
引入dtd约束
1、Mybatis配置文件在文档声明处,引入了一个dtd约束文件,他就是用来约束Mybatis核心配置文件中的标签语法规则的。
2、有了约束文件之后,就有提示了,联网的时候文件可以自动导入,没有网络的时候需要和文件下载绑定一下。全局配置文件有一个dtd,sql文件有一个dtd。
Properties标签
1、Properties标签用来引入外部properties类型配置文件的配置。
2、resource:引入类路径下的配置文件,源码包是类路径的开始,就是java包下,编译之后就是classes目录下,我们的Sp项目也是如此。
3、url:引入互联网或者磁盘中的配置文件
4、引入properteis文件之后,通过${key}就可以获取相应的值。
5、Spring整合Mybatis之后,这个连接池配置操作直接交给了Spring来做,非常方便,所有这个标签基本不用了。