hibernate应用实例

一、在Java应用中使用Hibernate的步骤

  • 创建Hibernate的配置文件
  • 创建持久化类
  • 创建对象-关系映射文件
  • 通过Hibernate API编写访问数据库的代码

 二、Helloapp应用的结构

三、Hibernate的配置文件(hibernate.properties)

  1. hibernate.dialect=org.hibernate.dialect.MySQLDialect  
  2. hibernate.connection.driver_class=com.mysql.jdbc.Driver  
  3. hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB  
  4. hibernate.connection.username=root  
  5. hibernate.connection.password=1234  
  6. hibernate.show_sql=true  
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/SAMPLEDB
hibernate.connection.username=root
hibernate.connection.password=1234
hibernate.show_sql=true


 

四、创建持久化类Customer

  • 持久化类符合JavaBean的规范,包含一些属性,以及与之对应的getXXX()和setXXX()方法。
  • 持久化类有一个id属性,用来惟一标识Customer类的每个对象。在面向对象术语中,这个id属性被称为对象标识符(OID,Object Identifier),通常它都用整数表示
  • Hibernate要求持久化类必须提供一个不带参数的默认构造方法 
  1. package mypack;  
  2. import java.io.Serializable;  
  3. import java.sql.Date;  
  4. import java.sql.Timestamp;  
  5.   
  6. public class Customer implements Serializable {  
  7.   private Long id;  
  8.   private String name;  
  9.   private String email;  
  10.   private String password;  
  11.   private int phone;  
  12.   private String address;  
  13.   private char sex;  
  14.   private boolean married;  
  15.   private String description;  
  16.   private byte[] image;  
  17.   private Date birthday;  
  18.   private Timestamp registeredTime;  
  19.   
  20.   public Customer(){}  
  21.   
  22.   public Long getId(){  
  23.     return id;  
  24.   }  
  25.   
  26.   private void setId(Long id){  
  27.     this.id = id;  
  28.   }  
  29.   
  30.   public String getName(){  
  31.     return name;  
  32.   }  
  33.   
  34.   public void setName(String name){  
  35.     this.name=name;  
  36.   }  
  37.   
  38.   public String getEmail(){  
  39.     return email;  
  40.   }  
  41.   
  42.   public void setEmail(String email){  
  43.     this.email =email ;  
  44.   }  
  45.   
  46.   public String getPassword(){  
  47.     return password;  
  48.   }  
  49.   
  50.   public void setPassword(String password){  
  51.       this.password =password ;  
  52.   }  
  53.   
  54.   public int getPhone(){  
  55.     return phone;  
  56.   }  
  57.   
  58.   public void setPhone(int phone){  
  59.     this.phone =phone ;  
  60.   }  
  61.   
  62.   public String getAddress(){  
  63.     return address;  
  64.   }  
  65.   
  66.   public void setAddress(String address){  
  67.     this.address =address ;  
  68.   }  
  69.   public char getSex(){  
  70.     return sex;  
  71.   }  
  72.   
  73.   public void setSex(char sex){  
  74.     this.sex =sex ;  
  75.   }  
  76.   
  77.   public boolean isMarried(){  
  78.     return married;  
  79.   }  
  80.   
  81.   public void setMarried(boolean married){  
  82.     this.married =married ;  
  83.   }  
  84.   
  85.   public String getDescription(){  
  86.       return description;  
  87.   }  
  88.   
  89.   public void setDescription(String description){  
  90.       this.description =description ;  
  91.   }  
  92.   
  93.   public byte[] getImage() {  
  94.         return this.image;  
  95.   }  
  96.   
  97.   public void setImage(byte[] image) {  
  98.         this.image = image;  
  99.   }  
  100.   
  101.   public Date getBirthday() {  
  102.         return this.birthday;  
  103.   }  
  104.   
  105.   public void setBirthday(Date birthday) {  
  106.         this.birthday = birthday;  
  107.   }  
  108.   
  109.   public Timestamp getRegisteredTime() {  
  110.         return this.registeredTime;  
  111.   }  
  112.   
  113.   public void setRegisteredTime(Timestamp registeredTime) {  
  114.         this.registeredTime = registeredTime;  
  115.   }  
  116.   
  117. }  
package mypack;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;

public class Customer implements Serializable {
  private Long id;
  private String name;
  private String email;
  private String password;
  private int phone;
  private String address;
  private char sex;
  private boolean married;
  private String description;
  private byte[] image;
  private Date birthday;
  private Timestamp registeredTime;

  public Customer(){}

  public Long getId(){
    return id;
  }

  private void setId(Long id){
    this.id = id;
  }

  public String getName(){
    return name;
  }

  public void setName(String name){
    this.name=name;
  }

  public String getEmail(){
    return email;
  }

  public void setEmail(String email){
    this.email =email ;
  }

  public String getPassword(){
    return password;
  }

  public void setPassword(String password){
      this.password =password ;
  }

  public int getPhone(){
    return phone;
  }

  public void setPhone(int phone){
    this.phone =phone ;
  }

  public String getAddress(){
    return address;
  }

  public void setAddress(String address){
    this.address =address ;
  }
  public char getSex(){
    return sex;
  }

  public void setSex(char sex){
    this.sex =sex ;
  }

  public boolean isMarried(){
    return married;
  }

  public void setMarried(boolean married){
    this.married =married ;
  }

  public String getDescription(){
      return description;
  }

  public void setDescription(String description){
      this.description =description ;
  }

  public byte[] getImage() {
        return this.image;
  }

  public void setImage(byte[] image) {
        this.image = image;
  }

  public Date getBirthday() {
        return this.birthday;
  }

  public void setBirthday(Date birthday) {
        this.birthday = birthday;
  }

  public Timestamp getRegisteredTime() {
        return this.registeredTime;
  }

  public void setRegisteredTime(Timestamp registeredTime) {
        this.registeredTime = registeredTime;
  }

}

  注意:

  • getXXX()和setXXX()方法可以采用任意的访问级别,他的命名规则必须符合特定的命名规则,“get”和“set”后面紧跟属性的名字,并且属性名的首字母为大写,如name属性的get方法为getName()。
  •  如果持久化类的属性为boolean类型,那么它的get方法名可以用get做前缀也可以用is做前缀。

五、创建数据库Schema

  1. drop database if exists SAMPLEDB;  
  2. create database SAMPLEDB;  
  3. use SAMPLEDB;  
  4.   
  5. create table CUSTOMERS (  
  6.   ID bigint not null primary key,  
  7.   NAME varchar(15) not null,  
  8.   EMAIL varchar(128) not null,  
  9.   PASSWORD varchar(8) not null,    
  10.   PHONE int ,    
  11.   ADDRESS varchar(255),  
  12.   SEX char(1) ,  
  13.   IS_MARRIED bit,  
  14.   DESCRIPTION text,  
  15.   IMAGE blob,  
  16.   BIRTHDAY date,  
  17.   REGISTERED_TIME timestamp  
  18. );  
drop database if exists SAMPLEDB;
create database SAMPLEDB;
use SAMPLEDB;

create table CUSTOMERS (
  ID bigint not null primary key,
  NAME varchar(15) not null,
  EMAIL varchar(128) not null,
  PASSWORD varchar(8) not null,  
  PHONE int ,  
  ADDRESS varchar(255),
  SEX char(1) ,
  IS_MARRIED bit,
  DESCRIPTION text,
  IMAGE blob,
  BIRTHDAY date,
  REGISTERED_TIME timestamp
);


 

六、创建对象-关系映射文件Customer.hbm.xml
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  3.   
  4. <hibernate-mapping>  
  5.   <class name="mypack.Customer" table="CUSTOMERS">  
  6.     <id name="id" column="ID" type="long">  
  7.       <generator class="increment"/>  
  8.     </id>  
  9.     <property name="name"  column="NAME"  type="string" not-null="true" />    
  10.     <property name="email"     column="EMAIL"     type="string" not-null="true" />   
  11.     <property name="password"  column="PASSWORD"  type="string" not-null="true"/>   
  12.     <property name="phone"     column="PHONE"     type="int" />   
  13.     <property name="address"   column="ADDRESS"   type="string" />   
  14.     <property name="sex"       column="SEX"       type="character"/>    
  15.     <property name="married"   column="IS_MARRIED"  type="boolean"/>        
  16.     <property name="description"   column="DESCRIPTION"  type="text"/>        
  17.     <property name="image"         column="IMAGE"        type="binary"/>  
  18.     <property name="birthday"      column="BIRTHDAY"     type="date"/>  
  19.     <property name="registeredTime" column="REGISTERED_TIME"  type="timestamp"/>    
  20.   </class>  
  21. </hibernate-mapping>  
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="mypack.Customer" table="CUSTOMERS">
    <id name="id" column="ID" type="long">
      <generator class="increment"/>
    </id>
    <property name="name"  column="NAME"  type="string" not-null="true" />  
    <property name="email"     column="EMAIL"     type="string" not-null="true" /> 
    <property name="password"  column="PASSWORD"  type="string" not-null="true"/> 
    <property name="phone"     column="PHONE"     type="int" /> 
    <property name="address"   column="ADDRESS"   type="string" /> 
    <property name="sex"       column="SEX"       type="character"/>  
    <property name="married"   column="IS_MARRIED"  type="boolean"/>      
    <property name="description"   column="DESCRIPTION"  type="text"/>      
    <property name="image"         column="IMAGE"        type="binary"/>
    <property name="birthday"      column="BIRTHDAY"     type="date"/>
    <property name="registeredTime" column="REGISTERED_TIME"  type="timestamp"/>  
  </class>
</hibernate-mapping>
  • <id>元素映射OID

                <generator>子元素用来设定标识符生成器。Hibernate提供了提供了多种内置的实现。

 

  • <property>元素映射值类型属性
              name属性:指定持久化类的属性的名字。
              column属性:指定与类的属性映射的表的字段名。
              type属性:指定Hibernate映射类型。Hibernate映射类型是Java类型与SQL类型的桥梁。

 

 

采用XML文件来配置对象-关系映射的优点:
  • Hibernate既不会渗透到上层域模型中,也不会渗透到下层数据模型中。
  • 软件开发人员可以独立设计域模型,不必强迫遵守任何规范。
  • 数据库设计人员可以独立设计数据模型,不必强迫遵守任何规范。
  • 对象-关系映射不依赖于任何程序代码,如果需要修改对象-关系映射,只需修改XML文件,不需要修改任何程序,提高了软件的灵活性,并且使维护更加方便。
七、创建BusinessService类

 

  1. package mypack;  
  2.   
  3. import javax.servlet.*;  
  4. import org.hibernate.*;  
  5. import org.hibernate.cfg.Configuration;  
  6. import java.io.*;  
  7. import java.sql.Date;  
  8. import java.sql.Timestamp;  
  9. import java.util.*;  
  10.   
  11. public class BusinessService{  
  12.   public static SessionFactory sessionFactory;  
  13.     
  14.   /** 初始化Hibernate,创建SessionFactory实例 */  
  15.   static{  
  16.     try{  
  17.       // 根据默认位置的Hibernate配置文件的配置信息,创建一个Configuration实例   
  18.       Configuration config = new Configuration();  
  19.       //加载Customer类的对象-关系映射文件   
  20.       config.addClass(Customer.class);  
  21.       // 创建SessionFactory实例 */   
  22.       sessionFactory = config.buildSessionFactory();  
  23.     }catch(RuntimeException e){e.printStackTrace();throw e;}  
  24.   }  
  25.     
  26.   /** 查询所有的Customer对象,然后调用printCustomer()方法打印Customer对象信息 */  
  27.   public void findAllCustomers(ServletContext context,PrintWriter out) throws Exception{  
  28.     Session session = sessionFactory.openSession(); //创建一个会话   
  29.     Transaction tx = null;  
  30.     try {  
  31.       tx = session.beginTransaction(); //开始一个事务   
  32.       Query query=session.createQuery("from Customer as c order by c.name asc");  
  33.       List customers=query.list();  
  34.       for (Iterator it = customers.iterator(); it.hasNext();) {  
  35.          printCustomer(context,out,(Customer) it.next());  
  36.       }  
  37.   
  38.       tx.commit(); //提交事务   
  39.   
  40.     }catch (RuntimeException e) {  
  41.       if (tx != null) {  
  42.          tx.rollback();  
  43.       }  
  44.       throw e;  
  45.     } finally {  
  46.        session.close();  
  47.     }  
  48.   }  
  49.   
  50.   /** 持久化一个Customer对象 */  
  51.   public void saveCustomer(Customer customer){  
  52.     Session session = sessionFactory.openSession();  
  53.     Transaction tx = null;  
  54.     try {  
  55.       tx = session.beginTransaction();  
  56.       session.save(customer);  
  57.       tx.commit();  
  58.   
  59.     }catch (RuntimeException e) {  
  60.       if (tx != null) {  
  61.         tx.rollback();  
  62.       }  
  63.       throw e;  
  64.     } finally {  
  65.       session.close();  
  66.     }  
  67.   }  
  68.   
  69.   /** 按照OID加载一个Customer对象,然后修改它的属性 */  
  70.   public void loadAndUpdateCustomer(Long customer_id,String address){  
  71.     Session session = sessionFactory.openSession();  
  72.     Transaction tx = null;  
  73.     try {  
  74.       tx = session.beginTransaction();  
  75.   
  76.       Customer c=(Customer)session.get(Customer.class,customer_id);  
  77.       c.setAddress(address);  
  78.       tx.commit();  
  79.   
  80.     }catch (RuntimeException e) {  
  81.       if (tx != null) {  
  82.         tx.rollback();  
  83.       }  
  84.       throw e;  
  85.     } finally {  
  86.       session.close();  
  87.     }  
  88.   }  
  89.   
  90.   /**删除Customer对象 */  
  91.   public void deleteCustomer(Customer customer){  
  92.     Session session = sessionFactory.openSession();  
  93.     Transaction tx = null;  
  94.     try {  
  95.       tx = session.beginTransaction();  
  96.       session.delete(customer);  
  97.       tx.commit();  
  98.   
  99.     }catch (RuntimeException e) {  
  100.       if (tx != null) {  
  101.         tx.rollback();  
  102.       }  
  103.       throw e;  
  104.     } finally {  
  105.       session.close();  
  106.     }  
  107.   }  
  108.     
  109.   /** 选择向控制台还是Web网页输出Customer对象的信息 */  
  110.   private void printCustomer(ServletContext context,PrintWriter out,Customer customer)throws Exception{  
  111.      if(context!=null)  
  112.        printCustomerInWeb(context,out,customer);  
  113.      else  
  114.        printCustomer( out,customer);  
  115.   }  
  116.     
  117.   /** 把Customer对象的信息输出到控制台,如DOS 控制台*/  
  118.   private void printCustomer(PrintWriter out,Customer customer)throws Exception{  
  119.     byte[] buffer=customer.getImage();  
  120.     FileOutputStream fout=new FileOutputStream("photo_copy.gif");  
  121.     fout.write(buffer);  
  122.     fout.close();  
  123.   
  124.     out.println("------以下是"+customer.getName()+"的个人信息------");  
  125.     out.println("ID: "+customer.getId());  
  126.     out.println("口令: "+customer.getPassword());  
  127.     out.println("E-Mail: "+customer.getEmail());  
  128.     out.println("电话: "+customer.getPhone());  
  129.     out.println("地址: "+customer.getAddress());  
  130.     String sex=customer.getSex()=='M'"男":"女";  
  131.     out.println("性别: "+sex);  
  132.     String marriedStatus=customer.isMarried()? "已婚":"未婚";  
  133.     out.println("婚姻状况: "+marriedStatus);  
  134.     out.println("生日: "+customer.getBirthday());  
  135.     out.println("注册时间: "+customer.getRegisteredTime());  
  136.     out.println("自我介绍: "+customer.getDescription());  
  137.   
  138.   }  
  139.   
  140.   /** 把Customer对象的信息输出到动态网页 */  
  141.   private void printCustomerInWeb(ServletContext context,PrintWriter out,Customer customer)throws Exception{  
  142.     //保存照片   
  143.     byte[] buffer=customer.getImage();  
  144.     String path=context.getRealPath("/");  
  145.     FileOutputStream fout=new FileOutputStream(path+"photo_copy.gif");  
  146.     fout.write(buffer);  
  147.     fout.close();  
  148.   
  149.     out.println("------以下是"+customer.getName()+"的个人信息------"+"<br>");  
  150.     out.println("ID: "+customer.getId()+"<br>");  
  151.     out.println("口令: "+customer.getPassword()+"<br>");  
  152.     out.println("E-Mail: "+customer.getEmail()+"<br>");  
  153.     out.println("电话: "+customer.getPhone()+"<br>");  
  154.     out.println("地址: "+customer.getAddress()+"<br>");  
  155.     String sex=customer.getSex()=='M'"男":"女";  
  156.     out.println("性别: "+sex+"<br>");  
  157.     String marriedStatus=customer.isMarried()? "已婚":"未婚";  
  158.     out.println("婚姻状况: "+marriedStatus+"<br>");  
  159.     out.println("生日: "+customer.getBirthday()+"<br>");  
  160.     out.println("注册时间: "+customer.getRegisteredTime()+"<br>");  
  161.     out.println("自我介绍: "+customer.getDescription()+"<br>");  
  162.     out.println("<img src='photo_copy.gif' border=0><p>");  
  163.   }  
  164.    public void test(ServletContext context,PrintWriter out) throws Exception{  
  165.   
  166.     Customer customer=new Customer();  
  167.     customer.setName("Tom");  
  168.     customer.setEmail("[email protected]");  
  169.     customer.setPassword("1234");  
  170.     customer.setPhone(55556666);  
  171.     customer.setAddress("Shanghai");  
  172.     customer.setSex('M');  
  173.     customer.setDescription("I am very honest.");  
  174.       
  175.     //设置Customer对象的image属性,它是字节数组,存放photo.gif文件中的二进制数据   
  176.     //photo.gif文件和BusinessService.class文件位于同一个目录下    
  177.     InputStream in=this.getClass().getResourceAsStream("photo.gif");  
  178.     byte[] buffer = new byte[in.available()];  
  179.     in.read(buffer);  
  180.     customer.setImage(buffer);  
  181.     //设置Customer对象的birthday属性,它是java.sql.Date类型    
  182.     customer.setBirthday(Date.valueOf("1980-05-06"));  
  183.   
  184.     saveCustomer(customer);  
  185.   
  186.     findAllCustomers(context,out);  
  187.     loadAndUpdateCustomer(customer.getId(),"Beijing");  
  188.     findAllCustomers(context,out);  
  189.     deleteCustomer(customer);  
  190.   }  
  191.   
  192.   public static void main(String args[]) throws Exception {  
  193.     new BusinessService().test(null,new PrintWriter(System.out,true));  
  194.     sessionFactory.close();  
  195.   }  
  196. }  
package mypack;

import javax.servlet.*;
import org.hibernate.*;
import org.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{
      // 根据默认位置的Hibernate配置文件的配置信息,创建一个Configuration实例
      Configuration config = new Configuration();
      //加载Customer类的对象-关系映射文件
      config.addClass(Customer.class);
      // 创建SessionFactory实例 */
      sessionFactory = config.buildSessionFactory();
    }catch(RuntimeException e){e.printStackTrace();throw e;}
  }
  
  /** 查询所有的Customer对象,然后调用printCustomer()方法打印Customer对象信息 */
  public void findAllCustomers(ServletContext context,PrintWriter out) throws Exception{
    Session session = sessionFactory.openSession(); //创建一个会话
    Transaction tx = null;
    try {
      tx = session.beginTransaction(); //开始一个事务
      Query query=session.createQuery("from Customer as c order by c.name asc");
      List customers=query.list();
      for (Iterator it = customers.iterator(); it.hasNext();) {
         printCustomer(context,out,(Customer) it.next());
      }

      tx.commit(); //提交事务

    }catch (RuntimeException e) {
      if (tx != null) {
         tx.rollback();
      }
      throw e;
    } finally {
       session.close();
    }
  }

  /** 持久化一个Customer对象 */
  public void saveCustomer(Customer customer){
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      session.save(customer);
      tx.commit();

    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      session.close();
    }
  }

  /** 按照OID加载一个Customer对象,然后修改它的属性 */
  public void loadAndUpdateCustomer(Long customer_id,String address){
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();

      Customer c=(Customer)session.get(Customer.class,customer_id);
      c.setAddress(address);
      tx.commit();

    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      session.close();
    }
  }

  /**删除Customer对象 */
  public void deleteCustomer(Customer customer){
    Session session = sessionFactory.openSession();
    Transaction tx = null;
    try {
      tx = session.beginTransaction();
      session.delete(customer);
      tx.commit();

    }catch (RuntimeException e) {
      if (tx != null) {
        tx.rollback();
      }
      throw e;
    } finally {
      session.close();
    }
  }
  
  /** 选择向控制台还是Web网页输出Customer对象的信息 */
  private void printCustomer(ServletContext context,PrintWriter out,Customer customer)throws Exception{
     if(context!=null)
       printCustomerInWeb(context,out,customer);
     else
       printCustomer( out,customer);
  }
  
  /** 把Customer对象的信息输出到控制台,如DOS 控制台*/
  private void printCustomer(PrintWriter out,Customer customer)throws Exception{
    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());

  }

  /** 把Customer对象的信息输出到动态网页 */
  private void printCustomerInWeb(ServletContext context,PrintWriter out,Customer customer)throws Exception{
    //保存照片
    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,PrintWriter out) throws Exception{

    Customer customer=new Customer();
    customer.setName("Tom");
    customer.setEmail("[email protected]");
    customer.setPassword("1234");
    customer.setPhone(55556666);
    customer.setAddress("Shanghai");
    customer.setSex('M');
    customer.setDescription("I am very honest.");
    
    //设置Customer对象的image属性,它是字节数组,存放photo.gif文件中的二进制数据
    //photo.gif文件和BusinessService.class文件位于同一个目录下 
    InputStream in=this.getClass().getResourceAsStream("photo.gif");
    byte[] buffer = new byte[in.available()];
    in.read(buffer);
    customer.setImage(buffer);
    //设置Customer对象的birthday属性,它是java.sql.Date类型 
    customer.setBirthday(Date.valueOf("1980-05-06"));

    saveCustomer(customer);

    findAllCustomers(context,out);
    loadAndUpdateCustomer(customer.getId(),"Beijing");
    findAllCustomers(context,out);
    deleteCustomer(customer);
  }

  public static void main(String args[]) throws Exception {
    new BusinessService().test(null,new PrintWriter(System.out,true));
    sessionFactory.close();
  }
}

  • saveCustomer()方法
该方法调用Session的save()方法,把Customer对象持久化到数据库中。
      
  1. tx = session.beginTransaction();  
  2.   
  3.        session.save(customer);  
  4.   
  5.        tx.commit();  
tx = session.beginTransaction();

       session.save(customer);

       tx.commit();
当运行session.save()方法时,Hibernate执行以下SQL语句:
     
  1. insert into CUSTOMERS (ID, NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX,  
  2.   
  3.       IS_MARRIED,DESCRIPTION, IMAGE, BIRTHDAY, REGISTERED_TIME)   
  4.   
  5.       values(1,'Tom','[email protected]','1234',55556666,'Shanghai','M',0,'I am very honest.', ☺,'1980-05-06',null)  
insert into CUSTOMERS (ID, NAME, EMAIL, PASSWORD, PHONE, ADDRESS, SEX,

      IS_MARRIED,DESCRIPTION, IMAGE, BIRTHDAY, REGISTERED_TIME) 

      values(1,'Tom','[email protected]','1234',55556666,'Shanghai','M',0,'I am very honest.', ☺,'1980-05-06',null)
在test()方法中并没有设置Customer对象的id属性,Hibernate会根据映射文件的配置,采用increment标识符生成器自动以递增的方式为OID赋值。在Customer.hbm.xml文件中相关的映射代码如下:
  
  1. <id name="id" column="ID" type="long">  
  2.   
  3.      <generator class="increment"/>  
  4.   
  5.   </id>  
    <id name="id" column="ID" type="long">

         <generator class="increment"/>

      </id>
  • findAllCustomers()方法
该方法通过Query接口查询所有的Customer对象。
  1. tx = session.beginTransaction(); //开始一个事务   
  2.   
  3. Query query=session.createQuery("from Customer as c order by c.name asc");  
  4.   
  5. List customers=query.list();  
  6.   
  7. for (Iterator it = customers.iterator(); it.hasNext();) {  
  8.   
  9.   printCustomer(context,out,(Customer) it.next());  
  10.   
  11. }  
  12.   
  13. tx.commit(); //提交事务  
tx = session.beginTransaction(); //开始一个事务

Query query=session.createQuery("from Customer as c order by c.name asc");

List customers=query.list();

for (Iterator it = customers.iterator(); it.hasNext();) {

  printCustomer(context,out,(Customer) it.next());

}

tx.commit(); //提交事务
Session的createQuery()方法的参数“from Customer as c order by c.name asc”使用的是Hibernate查询语言。运行Query.list()方法时, Hibernate执行以下SQL语句:
  1. select * from CUSTOMERS order by NAME asc;  
select * from CUSTOMERS order by NAME asc;
  • loadAndUpdateCustomer ()方法
该方法调用Session的get()方法,加载Customer对象,然后再修改Customer对象的属性。
     
  1. tx = session.beginTransaction();  
  2.   
  3.       Customer c=(Customer)session.get(Customer.class,customer_id);  
  4.   
  5.       c.setAddress(address); //修改内存中Customer对象的address属性   
  6.   
  7.       tx.commit();  
tx = session.beginTransaction();

      Customer c=(Customer)session.get(Customer.class,customer_id);

      c.setAddress(address); //修改内存中Customer对象的address属性

      tx.commit();
 
以上代码先调用Session的get()方法,它按照参数指定的OID从数据库中检索出匹配的Customer对象,Hibernate会执行以下SQL语句:
     
  1. select * from CUSTOMERS where ID=1;  
select * from CUSTOMERS where ID=1;

loadAndUpdateCustomer()方法接着修改Customer对象的address属性。那么,Hibernate会不会同步更新数据库中相应的CUSTOMERS表的记录呢?答案是肯定的。Hibernate采用脏检查机制,按照内存中的Customer对象的状态的变化,来同步更新数据库中相关的数据,Hibernate会执行以下SQL语句:
  1. update CUSTOMERS set NAME="Tom",EMAIL="[email protected]"…ADDRESS="Beijing"…  
  2.   
  3. where ID=1;  
      update CUSTOMERS set NAME="Tom",EMAIL="[email protected]"…ADDRESS="Beijing"…

      where ID=1;

尽管只有Customer对象的address属性发生了变化,但是Hibernate执行的update语句中会包含所有的字段。
  • deleteCustomer()方法
该方法调用Session的delete()方法,删除特定的Customer对象:
      
  1. tx = session.beginTransaction();  
  2.   
  3.       session.delete(customer);  
  4.   
  5.       tx.commit();  
tx = session.beginTransaction();

      session.delete(customer);

      tx.commit();

运行session.delete()方法时,Hibernate根据Customer对象的OID,执行以下SQL delete语句:
  1. delete from CUSTOMERS where ID=1;   
delete from CUSTOMERS where ID=1; 

 八、效果图

  

猜你喜欢

转载自zengshaotao.iteye.com/blog/1843484