一、简介
JDBC 回顾
传统的利用JDBC访问数据库的操作如下所示:
public void findStudent() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//注册mysql驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据的基本信息 url ,username,password
String url = "jdbc:mysql://localhost:3306/springdb";
String username = "root";
String password = "123456";
//创建连接对象
conn = DriverManager.getConnection(url, username, password);
//保存查询结果
List<Student> stuList = new ArrayList<>();
//创建Statement, 用来执行sql语句
stmt = conn.createStatement();
//执行查询,创建记录集,
rs = stmt.executeQuery("select * from student");
while (rs.next()) {
Student stu = new Student();
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setAge(rs.getInt("age"));
//从数据库取出数据转为Student对象,封装到List集合
stuList.add(stu);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//关闭资源
if (rs != null){
rs.close();
} if (stmt != null) {
stmt.close();
} if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 JDBC的缺陷 的缺陷
- 代码比较多,开发效率低
- 需要关注
Connection ,Statement, ResultSet
对象创建和销毁 - 对
ResultSet
查询的结果,需要自己封装为 List - 重复的代码比较多些
- 业务代码和数据库的操作混在一起
Hibernate 和 Mybatis
Hibernate:全自动全映射ORM框架,旨在消除 sql 。但是存在开发人员无法自主优化 sql 语句的缺点。
mybatis是优秀的基于java持久层的框架(半自动),它内部封装了jdbc,sql与java编码分离(sql单独提取到配置文件中,由开发者控制),开发者只需要关注sql语句本身(剩下的预编译、设置参数、执行sql、封装结果由框架完成)。
- 它使用了ORM(Object Relational Mapping)的思想实现了结果集的封装。
ORM:Object Relational Mapping 对象关系映射
将数据库表和实体类、实体类的属性对应起来,让我们可以实现操作实体类即操作数据表
mybatis 通过 xml或注解的方式将要执行的 statement(sql语句)配置起来,通过java对象 和statement中sql的动态参数进行映射生成最终执行的sql语句,最后由mybatis框架执行 语句并将结果映射为java对象返回。
MyBatis可以完成
-
注册数据库的驱动,例如
Class.forName(“com.mysql.jdbc.Driver”))
-
创建 JDBC中必须使用的
Connection , Statement, ResultSet对象
-
从 xml中获取中获取 sql,并执行 sql 语句,把
ResultSet
结果转换java对象
List<Student> list = new ArrayLsit<>(); ResultSet rs = state.executeQuery(“select * from student”); while(rs.next){ Student student = new Student(); student.setName(rs.getString(“name”)); student.setAge(rs.getInt(“age”)); list.add(student); }
-
关闭资源
ResultSet.close() , Statement.close() , Conenection.close()
二、 接口式编程(方便开发扩展)实现:helloword
第一步:mybatis 准备
下载mybatis: https://github.com/mybatis/mybatis-3/releases
第二步:搭建 Mybatis 环境
创建数据库 MySQL
CREATE TABLE `student` (
`id` int(11) NOT NULL ,
`name` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
创建 maven 工程并添加依赖
-
1、创建模板:
-
2、工程坐标:
-
3、删除默认创建的 App类
-
4、加入maven坐标依赖
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!--mysql驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> </dependencies>
- 加入 maven 插件
主要需要定义我们需要加载的配置文件 以及固定当前maven版本<build> <resources> <resource> <!--定义配置文件所在目录--> <directory>src/main/java</directory> <includes> <!--定义需要加载的配置文件--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle --> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle --> <plugin> <artifactId>maven-site-plugin</artifactId> <version>3.7.1</version> </plugin> <plugin> <artifactId>maven-project-info-reports-plugin</artifactId> <version>3.0.0</version> </plugin> </plugins> </pluginManagement> </build>
第三步:编写实体与接口
编写Student实体:
创建包 com.bjpowernode.domain
, 包中创建 Student类
package com.atguigu;
public class Student {
//属性名和列名一样
private Integer id;
private String name;
private String email;
private Integer age;
// set ,get , toString
}
编写 studentDao 的接口:
package com.atguigu;
import java.util.List;
public interface StudentDao {
//查询所有数据
List<Student> selectStudents();
}
第四步:使用 mapper 映射文件 来实现接口
使用配置文件来实现接口的要求如下:
- 在 dao 包中创建文件
StudentDao.xml
- 要
StudentDao.xml
文件名称和接口StudentDao
一样 ,区分大小写的一样。
配置文件(在Dao的同目录下创建即可)如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.StudentDao">
<!--
select:表示查询操作。
id: 你要执行的sql语法的唯一标识, mybatis会使用这个id的值来找到要执行的sql语句
可以自定义,但是要求你使用接口中的方法名称。
resultType:表示结果类型的, 是sql语句执行后得到ResultSet,遍历这个ResultSet得到java对象的类型。
值写的类型的全限定名称
-->
<select id="selectStudents" resultType="com.atguigu.Student" >
select id,name,email,age from student order by id
</select>
<!--插入操作-->
<insert id="insertStudent">
insert into student values(#{id},#{name},#{email},#{age})
</insert>
</mapper>
-
指定约束文件
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
mybatis-3-mapper.dtd
是约束文件的名称, 扩展名是dtd的。
约束文件作用:限制,检查在当前文件中出现的标签,属性必须符合mybatis的要求 -
mapper
是当前文件的根标签,必须的。
namespace:
叫做命名空间,唯一值的, 可以是自定义的字符串。
要求你使用dao接口的全限定名称。 -
在当前文件中,可以使用特定的标签,表示数据库的特定操作。
<select>:表示执行查询,select语句
<update>:表示更新数据库的操作, 就是在标签中 写的是update sql语句
<insert>:表示插入, 放的是insert语句
<delete>:表示删除, 执行的delete语句
第五步:创建 MyBatis 的主配置文件
-
首先设置配置文件的根目录
项目src/main
下创建resources目录,设置resources目录为 resources root -
然后创建名称为 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> <!--配置mybatis环境--> <environments default="mysql"> <!--id:数据源的名称--> <environment id="mysql"> <!--配置事务类型:使用JDBC事务(使用Connection的提交和回滚)--> <transactionManager type="JDBC"/> <!--数据源dataSource:创建数据库Connection对象 type: POOLED 使用数据库的连接池 --> <dataSource type="POOLED"> <!--连接数据库的四个要素--> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatistest1?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="admin123"/> </dataSource> </environment> </environments> <mappers> <!--告诉mybatis要执行的sql语句的位置--> <mapper resource="com/atguigu/StudentDao.xml"/> </mappers> </configuration>
-
支持中文的 url:
jdbc:mysql://localhost:3306/mybatistest1?useUnicode=true&characterEncoding=UTF-8
第六步:编写测试文档
加载主配置文件,然后通过主配置文件得到 sqlSession
对象,利用该对象访问具体的dao实现
(即这里的每个接口的xml文件)
import com.atguigu.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
@Test
public void testStart() throws Exception{
//访问mybatis读取student数据
//1.定义mybatis主配置文件的名称, 从类路径的根开始(target/clasess)
String config="mybatis.xml";
//2.读取配置文件
InputStream in = Resources.getResourceAsStream(config);
//3.创建 sqlsessionFactory 对象获取 sqlsession
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
//执行 sqlSession中的 selectList(),进行查询
List<Student> studentList = sqlSession.selectList("com.atguigu.StudentDao.selectStudents");
//循环输出查询结果
studentList.forEach(student -> System.out.println(student));
//关闭资源
sqlSession.close();
}
}
结果如下所示:
其中:
第七步:配置日志功能
mybatis.xml 文件
加入日志配置,可以在控制台输出执行的 sql语句和参数
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
结果如下:
基本的CURD
insert 方法
-
StudentDao 接口增加方法
int insertStudent(Student student);
-
StudentDao.xml
加入 sql 语句<insert id="insertStudent"> insert into student(id,name,email,age) values(#{id},#{name},#{email},#{age}) </insert>
-
增加测试方法
import com.atguigu.Student; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.apache.ibatis.io.Resources; import java.io.InputStream; import java.util.List; public class MyBatisTest { @Test public void testStart() throws Exception{ //访问mybatis读取student数据 //1.定义mybatis主配置文件的名称, 从类路径的根开始(target/clasess) String config="mybatis.xml"; //2.读取配置文件 InputStream in = Resources.getResourceAsStream(config); //3.创建 sqlsessionFactory 对象获取 sqlsession SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); SqlSession sqlSession = factory.openSession(); //执行 sqlSession中的 selectList(),进行查询 List<Student> studentList = sqlSession.selectList("com.atguigu.StudentDao.selectStudents"); //循环输出查询结果 studentList.forEach(student -> System.out.println(student)); //关闭资源 sqlSession.close(); } @Test public void testInsert() throws Exception{ //访问mybatis读取student数据 //1.定义mybatis主配置文件的名称, 从类路径的根开始(target/clasess) String config="mybatis.xml"; //2.读取配置文件 InputStream in = Resources.getResourceAsStream(config); //3.创建 sqlsessionFactory 对象获取 sqlsession SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); SqlSession sqlSession = factory.openSession(); //执行 sqlSession中的 selectList(),进行查询 List<Student> studentList = sqlSession.selectList("com.atguigu.StudentDao.selectStudents"); System.out.println("添加之前:"); //循环输出查询结果 studentList.forEach(student -> System.out.println(student)); //创建新的student对象 Student student = new Student(); student.setId(1); student.setAge(12); student.setEmail("test"); student.setName("insert"); //执行 insert int rows = sqlSession.insert("com.atguigu.StudentDao.insertStudent",student); //提交事务 sqlSession.commit(); System.out.println("添加后:"); studentList = sqlSession.selectList("com.atguigu.StudentDao.selectStudents"); studentList.forEach(s -> System.out.println(s)); //关闭资源 sqlSession.close(); } }
结果如下所示:
update 方法
-
StudentDao 接口
中增加方法int updateStudent(Student student);
-
StudentDao.xml
中增加 sql 语句<update id="updateStudent"> update student set age = #{age} where id=#{id} </update>
-
增加测试方法:
@Test
public void testUpdate() throws Exception{
//访问mybatis读取student数据
//1.定义mybatis主配置文件的名称, 从类路径的根开始(target/clasess)
String config="mybatis.xml";
//2.读取配置文件
InputStream in = Resources.getResourceAsStream(config);
//3.创建 sqlsessionFactory 对象获取 sqlsession
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession sqlSession = factory.openSession();
//执行 sqlSession中的 selectList(),进行查询
List<Student> studentList = sqlSession.selectList("com.atguigu.StudentDao.selectStudents");
System.out.println("修改之前:");
//循环输出查询结果
studentList.forEach(student -> System.out.println(student));
//创建新的student对象
Student student = new Student();
student.setId(1);
student.setAge(22);
//执行 insert
int rows = sqlSession.insert("com.atguigu.StudentDao.updateStudent",student);
//提交事务
sqlSession.commit();
System.out.println("添加后:");
studentList = sqlSession.selectList("com.atguigu.StudentDao.selectStudents");
studentList.forEach(s -> System.out.println(s));
//关闭资源
sqlSession.close();
}
结果如下:
delete 方法
-
增加接口方法
int deleteStudent(int id);
-
StudentDao.xml
增加 sql 语句<delete id="deleteStudent"> delete from student where id=#{studentId} </delete>
-
增加测试方法
三、MyBatis 对象分析
入门案例中遇到的对象
-
Resource 类
mybatis中负责读取主配置文件。他有很多的方法可以通过加载并解析资源文件来返回不同类型的IO流对象。 -
SqlSessionFactoryBuilder 类
SqlSessionFactory 的创 建 , 需要使用SqlSessionFactoryBuilder
对 象 的build() 方 法
。 由 于 SqlSessionFactoryBuilder 对象在创建完工厂对象后,就完成了其历史使命,即可被销毁。所以,一般会将 该 SqlSessionFactoryBuilder 对象创建为一个方法内的局部对象,方法结束,对象销毁。 -
SqlSessionFactory 接口
SqlSessionFactory 接口对象是一个重量级对象(系统开销大的对象) ,是线程安全的,所以一个应用 只需要一个该对象即可。创建SqlSession
需要使用 SqlSessionFactory 接口的的 openSession()方法。- openSession(true):创建一个有自动提交功能的 SqlSession
- openSession(false):创建一个非自动提交功能的 SqlSession
- openSession( ):同 openSession(false)
-
SqlSession 接口
SqlSession 接口对象用于执行持久化操作,一个 SqlSession 对应着一次数据库会话,一次会话以 SqlSession 对象的创建开始,以 SqlSession对象的关闭结束。- SqlSession 接口对象是线程不安全的,所以每次数据库会话结束之前,都需要马上调用 close() 方法,将其关闭
- SqlSession在方法内部创建,使用完毕后关闭。
创建 MyBatisUtil 优化代码
从上面的对象分析可以发现:Sqlsession的获得方法是固定的,因此可以将其写成一个工具类,方便调用。如下,下面代码采用单例模式进行:
package com.bjpowernode.utils;
import jdk.internal.util.xml.impl.Input;
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;
public class MyBatisUtils {
private static SqlSessionFactory factory = null;
static {
String config="mybatis.xml"; // 需要和你的项目中的文件名一样
try {
InputStream in = Resources.getResourceAsStream(config);
//创建SqlSessionFactory对象,使用SqlSessionFactoryBuild
factory = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取SqlSession的方法
public static SqlSession getSqlSession() {
SqlSession sqlSession = null;
if( factory != null){
sqlSession = factory.openSession();// 非自动提交事务
}
return sqlSession;
}
}
接下来我们就可以直接使用 MyBatisUtil 类了: