通过Hibernate API操纵数据库

来源:互联网 发布:伦敦玛丽女王大学 知乎 编辑:程序博客网 时间:2024/05/20 02:28
 
五、通过Hibernate API操纵数据库
例:BusinessService.java
package mypack;
 
import javax.servlet.*;
import net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;
import java.io.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.*;
 
public class BusinessService{
 public static SessionFactory sessionFactory;
 
        /** 初始化Hibernate,创建SessionFactory实例 */
 static{
    try{
      // Create a configuration based on the properties file we've put
      // in the standard place.
      Configuration config = new Configuration();
      config.addClass(Customer.class);
      // Get the session factory we can use for persistence
      sessionFactory = config.buildSessionFactory();
    }catch(Exception e){e.printStackTrace();}
 }
 
 public void findAllCustomers(ServletContext context,OutputStream out) throws Exception{
    // Ask for a session using the JDBC information we've configured
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      List customers=session.find("from Customer as c order by c.name asc");
      for (Iterator it = customers.iterator(); it.hasNext();) {
         printCustomer(context,out,(Customer) it.next());
      }
 
      // We're done; make our changes permanent
      tx.commit();
 
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
 }
 public void saveCustomer(Customer customer) throws Exception{
        // Ask for a session using the JDBC information we've configured
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      session.save(customer);
      // We're done; make our changes permanent
      tx.commit();
 
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
 }
 
 public void loadAndUpdateCustomer(Long customer_id,String address) throws Exception{
    // Ask for a session using the JDBC information we've configured
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
 
      Customer c=(Customer)session.load(Customer.class,customer_id);
      c.setAddress(address);
      // We're done; make our changes permanent
      tx.commit();
 
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
 }
 public void deleteAllCustomers() throws Exception{
    // Ask for a session using the JDBC information we've configured
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      session.delete("from Customer as c");
      // We're done; make our changes permanent
      tx.commit();
 
    }catch (Exception e) {
      if (tx != null) {
        // Something went wrong; discard all partial changes
        tx.rollback();
      }
      throw e;
    } finally {
      // No matter what, close the session
      session.close();
    }
 }
 
 private void printCustomer(ServletContext context,OutputStream out,Customer customer)throws Exception{
      if(out instanceof ServletOutputStream)
           printCustomer(context,(ServletOutputStream) out,customer);
       else
          printCustomer((PrintStream) out,customer);
 }
 private void printCustomer(PrintStream out,Customer customer)throws Exception{
   //save photo
    byte[] buffer=customer.getImage();
    FileOutputStream fout=new FileOutputStream("photo_copy.gif");
    fout.write(buffer);
    fout.close();
 
    out.println("------以下是"+customer.getName()+"的个人信息------");
    out.println("ID: "+customer.getId());
    out.println("口令: "+customer.getPassword());
    out.println("E-Mail: "+customer.getEmail());
    out.println("电话: "+customer.getPhone());
    out.println("地址: "+customer.getAddress());
    String sex=customer.getSex()=='M'? "":"";
    out.println("性别: "+sex);
    String marriedStatus=customer.isMarried()? "已婚":"未婚";
    out.println("婚姻状况: "+marriedStatus);
    out.println("生日: "+customer.getBirthday());
    out.println("注册时间: "+customer.getRegisteredTime());
    out.println("自我介绍: "+customer.getDescription());
 
 }
 private void printCustomer(ServletContext context,ServletOutputStream out,Customer customer)throws Exception{
    //save photo
    byte[] buffer=customer.getImage();
    String path=context.getRealPath("/");
    FileOutputStream fout=new FileOutputStream(path+"photo_copy.gif");
    fout.write(buffer);
    fout.close();
 
    out.println("------以下是"+customer.getName()+"的个人信息------"+"<br>");
    out.println("ID: "+customer.getId()+"<br>");
    out.println("口令: "+customer.getPassword()+"<br>");
    out.println("E-Mail: "+customer.getEmail()+"<br>");
    out.println("电话: "+customer.getPhone()+"<br>");
    out.println("地址: "+customer.getAddress()+"<br>");
    String sex=customer.getSex()=='M'? "":"";
    out.println("性别: "+sex+"<br>");
    String marriedStatus=customer.isMarried()? "已婚":"未婚";
    out.println("婚姻状况: "+marriedStatus+"<br>");
    out.println("生日: "+customer.getBirthday()+"<br>");
    out.println("注册时间: "+customer.getRegisteredTime()+"<br>");
    out.println("自我介绍: "+customer.getDescription()+"<br>");
    out.println("<img src='photo_copy.gif' border=0><p>");
 }
   public void test(ServletContext context,OutputStream out) throws Exception{
 
    Customer customer=new Customer();
    customer.setName("Tom");
    customer.setEmail("tom@yahoo.com");
    customer.setPassword("1234");
    customer.setPhone(55556666);
    customer.setAddress("Shanghai");
    customer.setSex('M');
    customer.setDescription("I am very honest.");
 
    InputStream in=this.getClass().getResourceAsStream("photo.gif");
    byte[] buffer = new byte[in.available()];
    in.read(buffer);
    customer.setImage(buffer);
    customer.setBirthday(Date.valueOf("1980-05-06"));
 
    saveCustomer(customer);
 
    findAllCustomers(context,out);
    loadAndUpdateCustomer(customer.getId(),"Beijing");
    findAllCustomers(context,out);
 
    deleteAllCustomers();
 }
 
 public static void main(String args[]) throws Exception {
    new BusinessService().test(null,System.out);
    sessionFactory.close();
 }
 
}
 
(1)       Hibernate的初始化
静态代码块负责Hibernate的初始化工作,如读取Hibernate的配置信息及对象-关系映射信息,最后创建SessionFactory实例。
初始化过程如下步骤:
a.
创建一个Configuration类的实例,Configuration类的构造方法把默认文件路径下的hibernate.propertyes配置文件中的配置信息读入到内存:
                 Configuration config=new Configuration();
b.
调用Configuration类的addClass(Customer.class)方法:
                 config.addClass(Customer.class);
c.
调用Configuration类的buildSessionFactory()方法:
                 sessionFactory=config.buildsessionFactory();
该方法创建一个SessionFactory实例。SessionFactory代表一个数据库存储源,如果应用只有一个数据库存储源,那么只需创建一个SessionFactory实例。
SessionFactory对象创建后,该对象不和Configuration对象关联。因此,如果再修改Configuration对象包含的配置信息,不会对SessionFactory对象有任何影响。
PS
Java语言是纯面向对象的语言,因此不可能像C语言那样直接操纵内存,因此若有提到缓存的概念,指的是java对象的属性(通常是一些集合类型的属性)占用的内存空间。
如果对象的缓存很大,就称为重量级对象;若很小,就称为轻量级对象。
SessionFactory
的缓存可分为两类:内置缓存和外置缓存(是一个可配置的缓存插件)
(2)       Hibernate的许多类和接口都支持方法链编程风格,Configuration类的addClass()方法返回当前的Configuration实例,因此对于以下代码:
                 Configuration config=new Configuration();
                 config.addClass(Customer.class);
                 sessionFactory=config.buildSessionFactory();
如果用方法链编程风格,可以改写为:
                 sessionFactory=new Configuration()
                           .addClass(Custormer.class)
                           .buildSessionFactory();
(3)       访问HibernateSession接口
初始化过程结束后,就可以调用SessionFactory实例的openSession()方法来获取Session实例,然后通过它执行访问数据库的操作。
        a. save()
方法:把Java对象保存数据库中;
        b. update()
方法:
        c. delete()
方法:
        d. load()
方法:从数据库中加载Java对象;
       e. find()
方法:从数据库中查询Java对象。
通常将每一个Session实例和一个数据库事务绑定,也就是说,每执行一个数据库事务,都应该先创建一个新的Session实例。
如果事务执行中出现异常,应该撤消事务。
无论事务执行成功与否,最后都应该调用Sessionclose()方法,从而释放Session实例占用的资源。
以下代码演示了用Session来执行事务的流程,其中Transaction类用来控制事务。
          Session session=sessionFactory.openSession();
          Transaction tx=null;
        try{
                 tx=session.beginTransaction();
                  //
执行事务
                  …
                  //
提交事务
                 tx.commit();
          }catch(Exception e){
                  //
如果出现异常,则撤销事务
                 if(tx!=null) tx.rollback();
                throw e;
        } finally{
                  //
无论事务执行是否成功,都关闭Session
                 session.close();
        }

 
原创粉丝点击