1.什么是jdbc
Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。
java中使用jdbc进行查询的过程:
//新建一个用于查询的account类
import java.io.Serializable;
import java.util.Objects;
public class Account implements Serializable {
private int id;
private String name;
private double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Account() {
}
public Account(int id, String name, double money) {
this.id = id;
this.name = name;
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
使用传统的jdbc技术实现对数据库的查询操作
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;
public class Jdbc {
public static void main(String[] args) {
InputStream is = Jdbc.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
Connection connection =null;
PreparedStatement statement =null;
ArrayList<Account> accounts = new ArrayList<>();
try {
properties.load(is);
String driver = (String) properties.get("driver");
String url = (String) properties.get("url");
String username = (String) properties.get("user");
String password = (String) properties.get("password");
//注册驱动
Class.forName(driver);
//获取连接
connection = DriverManager.getConnection(url, username, password);
String sql = "select * from account";
//获取预编译的statement对象
statement = connection.prepareStatement(sql);
//进行数据查询,获取结果集
ResultSet resultSet = statement.executeQuery();
//遍历结果集
while (resultSet.next()) {
Account account = new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getDouble("money"));
accounts.add(account);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement!=null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
for (Account account : accounts) {
System.out.println(account);
}
}
}
从上面的代码可以看出,使用jdbc技术连接数据库需要经历一系列的步骤,先要加载驱动,然后获取连接,获取预处理对象,然后通过预处理对象进行查询,得到结果集。查询结束后还需要关闭连接。这一系列的过程都需要我们自己手动去实现,包括对结果集的遍历封对象,可见代码的冗余,这就需要一个工具类来帮我们做这一件事,下面开始介绍mybatis框架。
2.什么是mybatis
MyBatis是一个持久层ORM框架,何为ORM,它的全称为Object Relational Mapping ,也就是对象关系映射,通俗点讲就是让实体类的属性名与数据库中的列名一一对应,通过这样的方法封装对象。 mybatis框架的用法有两种:一种是通过xml配置的方式,一种是通过注解的方式。xml需要放在resource目录下与dao的路径名一样的包中,否则xml配置不会生效,而注解的话只需要在dao中需要与数据库交互的方法上添加相应的注解即可,下面用注解的方式来实现对数据库的查询功能。
无论是用注解还是xml的方式,都需要先配置数据库连接资源,即SqlMapConfig.xml
下面是SqlMapConfig.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>
<properties resource="jdbc.properties"/>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件-->
<mappers>
//xml与注解的方式在此处有所不同,如果是注解的话指定package下的包名即可,而使用xml的话需要指定对应的映射配置文件即mapper中的resource
<package name="sun.han.dao"/>
//<mapper resource="sun.han.dao.AccountDao.xml"/>
</mappers>
</configuration>
新建一个持久层接口,里面只有一个查询所有方法,通过注解的方式实现查询功能。
import org.apache.ibatis.annotations.Select;
import sun.han.domain.Account;
import java.util.List;
public interface AccountDao {
@Select("select * from account ")
List<Account> findAll();
}
测试查询功能是否可以正常实现。
public static void main(String[] args) {
InputStream is = Test.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sessionFactory = factoryBuilder.build(is);
SqlSession session = sessionFactory.openSession();
AccountDao accountDao = session.getMapper(AccountDao.class);
List<Account> accounts = accountDao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
}
通过上述代码可以看出,使用mybatis以后,生成的结果集不需要我们自己来封装对象,mybatis以经帮我们完成了,并且不需要我们来手动注册驱动以及获取连接。还有通过注解的方式我们不需要实现dao接口,就可以完成dao的查询功能,提高了编码是效率与准确性。总的来说mybatis是基于jdbc而优于Jdbc,除上面所说的之外,MyBatis还对JDBC操作数据库做了一些别的优化: 提供了一级和二级缓存,提高了程序性能。mybatis使用动态SQL语句,提高了SQL维护。(此优势是基于XML配置)。