前言
回顾之前 不使用 mybatis 框架,我们是怎么通过Java 操作数据库的= "jdbc"
前提:使用maven 构建的项目
1 添加 关于jdbc 的依赖,以及辅助操作数据库的 commons-dubli jar包
- 截取 前后端项目
2 添加配置文件里面内容有:数据库三件套: username,password,url 。数据库驱动
db.properties 配置文件
driverClass=com.mysql.cj.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/arimethic?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username=root
password=123456
3 添加 加载 配置文件的类,还包括 连接数据库,关闭 各个资源的方法
jdbcUtil 类【工具类】
package it.projiect3.util;
import java.sql.*;
import java.util.Properties;
public class jdbcUtil {
//读取配置文件内容,使用 static 静态代码块
private static Properties properties=new Properties();
static {
try {
properties.load(jdbcUtil.class.getClassLoader().getResourceAsStream("db.properties"));
Class.forName(properties.getProperty("driverClass"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getCollection() throws SQLException {
String jdbcUrl = properties.getProperty("jdbcUrl");
String userName = properties.getProperty("username");
String userPassword = properties.getProperty("password");
return DriverManager.getConnection(jdbcUrl,userName,userPassword);
}
public static void close(Connection conn,Statement stmt, ResultSet rs) {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void close(Connection conn){
close(conn,null,null);
}
}
4举例: 查询所有数据
- 截取 前后端项目部分代码
StudentDaoImpl 类
@Override
public Student selectAll(Student student) {
QueryRunner queryRunner = new QueryRunner();
Connection conn=null;
try {
conn=getCollection();
String sql="select id,student_name studentName ,student_password studentPassword from student where student_name=? and student_password=?";
return queryRunner.query(conn, sql,new BeanHandler<>(Student.class) ,student.getStudentName(),student.getStudentPassword());
} catch (SQLException e) {
throw new RuntimeException(e);
}finally {
close(conn);
}
}
通过以上的了解,发现即使 使用 jdbc 操作数据库。其中还有 许多重复,且繁琐的操作。是否可以通过学习新的知识,节省部分代码和相关的操作呢?
Mybatis 框架介绍
MyBatis 是一款优秀的轻量级 Java 持久层框架,主要用于简化数据库操作。以下是关于 MyBatis 的基本介绍:
1. 核心功能
自定义 SQL 支持:MyBatis 允许开发者手动编写 SQL 语句,而不是完全依赖于 ORM 自动生成。这种方式提供了更高的灵活性和性能优化能力。
高级映射:通过 XML 或注解,MyBatis 可以将 Java 对象(POJO)与数据库表进行映射。
动态 SQL:MyBatis 提供了强大的动态 SQL 功能,可以根据业务逻辑动态生成 SQL 语句,减少冗余代码。
存储过程支持:支持调用数据库存储过程。
2. 工作原理
MyBatis 通过配置文件(XML 或注解)定义 SQL 映射关系,将 Java 方法与 SQL 语句关联起来。它封装了 JDBC 的繁琐操作,如资源管理、参数设置和结果集处理。
3. 优点
简化开发:减少了大量的 JDBC 代码,简化了异常处理和资源管理。
高性能:允许开发者直接优化 SQL,适合对性能要求较高的场景。
灵活性高:开发者可以自由编写 SQL,充分发挥数据库性能。
易于学习:配置简单,文档详尽,对熟悉 SQL 和 Java 的开发者非常友好。
轻量级:启动时间短,内存占用小,对现有项目侵入性低。
良好的缓存机制:支持一级缓存(SqlSession 级别)和二级缓存(命名空间级别),可显著提升性能。