hibernate和jdbC都是操作数据库的框架,那么既然有了jdbC,为什么又要学习hibernate呢?
首先我们先来了解一下它们各自的优缺点。
jdbC:
缺点:
1、查询语句比较繁琐
注:因为使用jdbC查询语句的时候,要把数据封装在ResultSet中,而且读取里面的数据还要判断里面是否有内容。
2、在关闭资源的时候,本来就是在finally里面关闭资源,但是在finally代码块里面,还要进行try、catch,
public class JdbcDemo4 {
public static void main(String[] args){
List<Users> users = new ArrayList<Users>();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
//获得驱动
Class.forName("com.mysql.jdbc.Driver");
//获得链接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day14", "root", "sorry");
stmt = conn.createStatement();
//查询语句
rs = stmt.executeQuery("select id,name,password,email,birthday from users");
//判断集合是否还有元素
while(rs.next()){
Users u = new Users();
u.setId(rs.getInt("id"));
u.setName(rs.getString("name"));
u.setPassword(rs.getString("password"));
u.setEmail(rs.getString("email"));
u.setBirthday(rs.getDate("birthday"));
users.add(u);
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
//接下来的两端代码,就是不听的try/catch
// try{
// if(rs!=null){
// rs.close();
// }
// }catch(Exception e){
// e.printStackTrace();
// }finally{
// try{
// if(stmt!=null){
// stmt.close();
// }
// }catch(Exception e){
// e.printStackTrace();
// }finally{
// try{
// if(conn!=null){
// conn.close();
// }
// }catch(Exception e){
// e.printStackTrace();
// }
// }
// }
//如果不为空的时候,说明已经获得了资源,那么我们在关闭的时候要释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
}
3、jdbC没有实现数据的缓存,在面对需要不断向数据库发送请求的情况时,效率非常不乐观
4、sql语句的移植性不好,比如jdbC的分页跟Oracle是不一样的,如果把数据库改成Oracle,那么代码就要重写。
优点:
1、因为jdbC是原始的操作数据库的框架,所以其效率比较高
2、因为它是原始,所以封装的内容不多,可控性好;比如struts2框架,封装的内容 太多了,可控性差。
hibernate的缺点:
1、因为hibernate的操作数据库的代码是其内部生成的,所以程序员对sql语句不好把控
2、由于上面的原因,对于有庞大数据量的数据库(超过千万级别),也不适合使用hibernate,因为发出了sql语句会导致操作数据库的效率低
优点:、
1、操作简单,再也不用频繁的try,catch
2、hibernate实现了数据的缓存,并且有三级缓存分别是:一级缓存,二级缓存和查询缓存
3、因为hibernate是ormapping框架(object-relation mapping对象关系映射),并且ormapping是面向对象的,所以移植性也会比较好