JDBC缺点:
1. 编写的SQL语句很长,不仅繁琐还容易出错。Sql语句硬编码到java代码中,如果修改,需要重新编译java代码,不利于系统维护。
2. 读取数据时,需要编写多条getString()或getInt()语句从数据库取出各个字段,不仅枯燥,而且工作量巨大。
3.数据库连接,使用时创建、不使用的时候释放,对数据库进行频繁连接开启和关闭,造成数据库资源浪费。
Hibernate框架搭建:
导入Hibernate的jar包和数据库驱动包
1..创建实体类
public class Dept implements Serializable{ private Integer deptNo; private String deptName; private String location; public Integer getDeptNo() { return deptNo; } public void setDeptNo(Integer deptNo) { this.deptNo = deptNo; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } }
2.编写映射文件
(实体类不具备持久化操作的能力,为了使其具备这种能力,需要告hibernate框架将实体类映射到数据库哪个表)
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.hibernatedemo.entity.Dept" table="dept" catalog="test"> <id name="deptNo" type="java.lang.Integer"> <column name="deptNo" /> <!--class="assigned": 没有在数据库里设置,由程序自己设自增 --> <!-- <generator class="assigned" /> --> <!--class="identity": 需要在数据库里设置主键自增 --> <generator class="identity" /> </id> <property name="deptName" type="java.lang.String"> <column name="deptName" length="50" /> </property> <property name="location" type="java.lang.String"> <column name="location" length="50" /> </property> </class> </hibernate-mapping>
3.编写Hibernate配置文件(hibernate.cfg.xml)
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <!-- 数据库URL --> <property name="connection.url"> jdbc:mysql://localhost:3306/test </property> <!-- 数据库JDBC驱动 --> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <!-- 数据库的用户名和密码 --> <property name="connection.username">root</property> <property name="connection.password"></property> <!-- 每个数据库都有其对应的方言(Dialect)以匹配其平台特性--> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- Session由当前执行的线程来跟踪管理 --> <property name="current_session_context_class">thread</property> <!-- 输出所有的sql语句到控制台 --> <property name="show_sql">true</property> <!-- 格式化sql语句 --> <property name="format_sql">true</property> <!-- 声明实体类映射文件 --> <mapping resource="com/hibernatedemo/entity/Dept.hbm.xml" /> </session-factory> </hibernate-configuration>
4. 进行数据库简单操作测试配置(DeptAddTest)
(1)插入数据
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.hibernatedemo.entity.Dept; public class DeptAddTest { public static void main(String[] args){ Configuration conf = null; SessionFactory sf = null; Session session = null; Transaction tx = null; try { //1.读取并解析配置文件及映射文件 conf = new Configuration().configure(); //2.依据配置文件和映射文件信息,创建SessionFactory sf = conf.buildSessionFactory(); //3.打开session //方法一:openSession,需要关闭Session //方法二:getCurrentSession,并设置<property name="current_session_context_class">thread</property>,不需要关闭session //session = sf.openSession(); session = sf.getCurrentSession(); //4.开始一个事务 tx = session.beginTransaction(); //5.数据库操作 Dept dept = new Dept(); //dept.setDeptNo(12);//mysql或者sqlserver数据库自动增长,主键identity,数据库自动增长,主键不用赋值 dept.setDeptName("开发部"); dept.setLocation("西青区"); session.save(dept); //6.提交事务 tx.commit(); //7.关闭Session //方法一:openSession,需要关闭session //方法二:getCurrentSession,并设置<property name="current_session_context_class">thread</property>,不需要关闭 //session.close(); } catch (HibernateException e) { // TODO: handle exception e.printStackTrace(); tx.rollback(); //遇到异常,事务回滚 } } }
(2)查询数据有get和load两种方法
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.hibernatedemo.entity.Dept; public class DeptQueryByKeyGetTest { public static void man(String[] args){ Configuration conf=null; SessionFactory sf=null; Session session=null; Transaction tx=null; try{ //1、读取并解析配置文件以及映射文件 conf=new Configuration().configure(); //读取的是hibernate.cfg.xml配置文件 //2、依据配置文件和映射文件信息,创建SessionFactory sf=conf.buildSessionFactory(); //3、打开session //方法一:openSession,需要关闭session //session=sf.openSession(); //方法二:getCurrentSession,并设置<property name="current_session_context_class">thread</property>,不需要关闭session session=sf.getCurrentSession(); //4、开始一个事务 tx=session.beginTransaction(); //5、数据库操作 Dept dept=new Dept(); //用session.get()方法 dept=(Dept)session.get(Dept.class, 3);//数据库中存在 //dept=(Dept)session.get(Dept.class, 10);//数据库中不存在,会返回NULL; //用session。load()方法 //dept=(Dept)session.load(Dept.class, 3); //数据库中存在 //dept=(Dept)session.load(Dept.class, 10); //数据库中不存在,会抛出异常; System.out.println("部门名称:"+dept.getDeptName()+";地区:"+dept.getLocation()); //6、提交事务 tx.commit(); //7、关闭资源(session) //方法一:openSession,需要关闭session // session.close(); //方法二:getCurrentSession,并设置<property name="current_session_context_class">thread</property>,不需要关闭session; }catch(HibernateException e){ e.printStackTrace(); } } }
(3) 删除和更改(主要代码)
删除:
try{ //1、读取并解析配置文件以及映射文件 conf=new Configuration().configure(); //读取的是hibernate.cfg.xml配置文件 //2、依据配置文件和映射文件信息,创建SessionFactory sf=conf.buildSessionFactory(); //3、打开session //方法一:openSession,需要关闭session //方法二:getCurrentSession,并设置<property name="current_session_context_class">thread</property>,不需要关闭session; // session=sf.openSession(); session=sf.getCurrentSession(); //4、开始一个事务 tx=session.beginTransaction(); //5、数据库操作 Dept dept=new Dept(); // 5.1、通过get()或者load()方法加载要修改的部门对象 dept = (Dept) session.get(Dept.class, 3); // dept=(Dept)session.load(Dept.class, 3); // 5.2、删除部门数据 session.delete(dept); //6、提交事务 tx.commit(); //7、关闭资源(session) //方法一:openSession,需要关闭session //方法二:getCurrentSession,并设置<property name="current_session_context_class">thread</property>,不需要关闭 // session.close(); }catch(HibernateException e){ e.printStackTrace(); tx.rollback(); //遇到异常,事务回滚 }
更改:
try{ // 1、读取并解析配置文件以及映射文件 conf = new Configuration().configure(); // 读取的是hibernate.cfg.xml配置文件 // 2、依据配置文件和映射文件信息,创建SessionFactory sf = conf.buildSessionFactory(); // 3、打开session // 方法一:openSession,需要关闭session // 方法二:getCurrentSession,并设置<property // name="current_session_context_class">thread</property>,不需要关闭session; // session=sf.openSession(); session = sf.getCurrentSession(); // 4、开始一个事务 tx = session.beginTransaction(); // 5、数据库操作 Dept dept = new Dept(); // 5.1、通过get()或者load()方法加载要修改的部门对象 dept = (Dept) session.get(Dept.class, 1); // dept=(Dept)session.load(Dept.class, 1); // 5.2、更新部门数据 dept.setDeptName("开发部1"); dept.setLocation("西青区1"); // session的连接、对象oid,数据持久化,不用session.update(dept),就可以完成更新 System.out.println("部门名称:" + dept.getDeptName()); // 6、提交事务 tx.commit(); // 7、关闭资源(session) // 方法一:openSession,需要关闭session // 方法二:getCurrentSession,并设置<property // name="current_session_context_class">thread</property>,不需要关闭 // session.close(); }catch(HibernateException e){ e.printStackTrace(); tx.rollback(); //遇到异常,事务回滚 }
至此已经搭建了Hibernate框架基本配置和使用,下一篇将整合增删查改DAO。