持久层框架,都是对jdbc的封装
单独使用jdbc开发就是原生态jdbc程序
mybatis开发dao的两种方法
1. 原始dao开发方法(程序需要编写dao接口和dao实现类)
2.mybatis的mapper接口(相当于dao接口代理开发方法(重点)
mybati配置文件是SqlMapConfig.xml
核心是输入输出映射
动态sql
高级结果集映射(一对一 对多 对多)
查询缓存(一级二级缓存)
与spring的整合
逆向工程
一、基于原生态jdbc出现的不足之处,进而学习mybatis框架
public class JdbcTest {
public static void main(String[] args) {
//数据库连接
Connection connection = null;
//预编译的Statement,使用预编译的Statement提高数据库性能
PreparedStatement preparedStatement = null;
//结果 集
ResultSet resultSet = null;
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//通过驱动管理类获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "123");
//定义sql语句 ?表示占位符
String sql = "select * from user where username = ?";
//获取预处理statement
preparedStatement = connection.prepareStatement(sql);
//设置参数,第一个参数为sql语句中参数的序号(从1开始),第二个参数为设置的参数值
preparedStatement.setString(1, "王五");
//向数据库发出sql执行查询,查询出结果集
resultSet = preparedStatement.executeQuery();
//遍历查询结果集
while(resultSet.next()){
System.out.println(resultSet.getString("id")+" "+resultSet.getString("username"));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
//释放资源
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(preparedStatement!=null){
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
不难看出原生态jdbc存在四点不足之处:
1.数据库连接创建、关闭频繁,资源浪费影响性能(连接池解决)
2. //定义sql语句 ?表示占位符
String sql = "select * from user where username = ?";
sql语句硬编码,不移维护。
3.preparedStatement.setString(1, "王五");
预编译的Statement占有位符号传参存在硬编码,不易维护
4.//遍历查询结果集
while(resultSet.next()){
System.out.println(resultSet.getString("id")+" "+resultSet.getString("username"));
}
结果集解析存在硬编码,SQL变化导致解析代码变化,不易维护。(截数据记录封装到pojo对象解析较为方便)
补充:
jdbc编程步骤(重点基础)
- 加载数据库驱动
- 创建并获取数据库链接
- 创建jdbc statement对象
- 设置sql语句
- 设置sql语句中的参数(使用preparedStatement)
- 通过statement执行sql并获取结果
- 对sql执行结果进行解析处理
- 释放资源(resultSet、preparedstatement、connection)