日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢(xún)
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
精通Hibernate:對(duì)象關(guān)系映射基礎(chǔ)

 1、持久化類(lèi)的屬性和訪問(wèn)方法
(1)持久化類(lèi)簡(jiǎn)介

大豐網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián)公司,大豐網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為大豐千余家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢(qián),請(qǐng)找那個(gè)售后服務(wù)好的大豐做網(wǎng)站的公司定做!

在Hibernate中持久化類(lèi)的訪問(wèn)方法有兩個(gè)調(diào)用者,一個(gè)是Java應(yīng)用程序,一個(gè)是Hibernate。值得注意的是,Java應(yīng)用程序不能訪問(wèn)持久化類(lèi)的private類(lèi)型的getXXX()、setXXX(),而Hibernate沒(méi)有這樣的限制。

(2)基本類(lèi)型屬性和包裝類(lèi)型屬性

Java有8種基本類(lèi)型:byte,short,char,int,long,float,double,boolean;與之對(duì)應(yīng)的Java提供了8種包裝類(lèi)型:Byte,Short,Character,Integer,Long,F(xiàn)loat,Double,Boolean?;绢?lèi)型與包裝類(lèi)型之間可以如下簡(jiǎn)單轉(zhuǎn)換:

 
 
 
 
  1. double prD=1;  
  2. //把double基本類(lèi)型轉(zhuǎn)換成Double包裝類(lèi)型  
  3. Double wrD=new Double(prD);  
  4. //把Double包裝類(lèi)型轉(zhuǎn)換成double基本類(lèi)型  
  5. prD=wrD.doubleValue(); 

Hibernate兩種類(lèi)型都是支持的。

(3)在持久化類(lèi)的訪問(wèn)方法中加入程序邏輯

(a)在Customer類(lèi)的getName()和setName()方法中加入程序邏輯

假如在Customer類(lèi)中有firstname屬性和lastname屬性,但是沒(méi)有name屬性,而數(shù)據(jù)庫(kù)CUSTOMERS表中只有NAME字段。當(dāng)Hibernate從數(shù)據(jù)庫(kù)中取得了CUSTOMERS表的NAME字段值后,會(huì)調(diào)用setName()方法,此時(shí)應(yīng)該讓Hibernate通過(guò)setName()方法來(lái)自動(dòng)設(shè)置firstname屬性和lastname。故要在setName()方法中加入額外的程序邏輯。

 
 
 
 
  1.  public String getName(){  
  2.    return firstname+ " "+lastname;  
  3. }  
  4.  
  5. public void setName(String name){  
  6.   StringTokenizer t=new StringTokenizer(name);  
  7.   firstname=t.nextToken();  
  8.   lastname=t.nextToken();  

在映射文件中此時(shí)直接映射name即可,無(wú)需映射firstname等。

 
 
 
 
  1.  

盡管在Customer類(lèi)中沒(méi)有定義name屬性,由于Hibernate并不會(huì)直接訪問(wèn)name屬性,而是通過(guò)getName()和setName()方法。只要在Customer.hbm.xml文件中映射了name屬性,HQL語(yǔ)句就能訪問(wèn):

 
 
 
 
  1. Query query=seesion.createQuery("from Customer as c where c.name='Tom'"); 

但是如果把Customer.hbm.xml文件中name屬性配置為:

 
 
 
 
  1.  

程序會(huì)直接去訪問(wèn)Customer實(shí)例中的name屬性,就會(huì)出現(xiàn)異常。

(b)在Customer類(lèi)的setOrders()方法中加入程序邏輯

假定Customer類(lèi)中有一個(gè)avgPrice屬性,表示訂單的平均價(jià)格,取值為它所關(guān)聯(lián)Order對(duì)象的price的平均值。在CUSTOMERS表中沒(méi)有AVG_PRICE字段??梢匀缦虏僮鳎?/p>

 
 
 
 
  1. public Double getAvgPrice(){  
  2.      return this.avgPrice;  
  3.  }  
  4.  private void setAvgPrice( Double avgPrice ){  
  5.      this.avgPrice = avgPrice;  
  6.  }  
  7.  public Double getTotalPrice(){  
  8.      return this.totalPrice;  
  9.  }  
  10.  private void setTotalPrice( Double totalPrice ){  
  11.      this.totalPrice = totalPrice;  
  12.  }  
  13.  
  14.  public void setOrders( Set orders ){  
  15.    this.orders = orders;  
  16.    calculatePrice();  
  17.  }  
  18.  public Set getOrders(){  
  19.    return orders;  
  20.  }//定義為一個(gè)Set  
  21.  private void calculatePrice(){  
  22.      double avgPrice = 0.0;  
  23.      double totalPrice = 0.0;  
  24.      int count=0;  
  25. /迭代計(jì)算orders里面所有price  
  26.      if ( getOrders() != null ){  
  27.        Iterator iter = getOrders().iterator();  
  28.        while( iter.hasNext() ){  
  29.          double orderPrice = ((Order)iter.next()).getPrice();  
  30.          totalPrice += orderPrice;  
  31.          count++;  
  32.        }  
  33.        // Set the price for the order from the calcualted value  
  34.        avgPrice=totalPrice/count;  
  35.        setAvgPrice( new Double(avgPrice) );  
  36.      }  
  37.  } 

在Customer.hbm.xml文件不用映射avgPrice,因?yàn)镠ibernate不會(huì)直接訪問(wèn)avgPrice屬性,也不會(huì)調(diào)用getavgPrice()和setavgPrice().

(c)在Customer類(lèi)的setSex()方法中加入數(shù)據(jù)驗(yàn)證邏輯

在持久化類(lèi)的訪問(wèn)方法中,還可以加入數(shù)據(jù)驗(yàn)證邏輯。

 
 
 
 
  1. public char getSex(){  
  2.    return this.sex;  
  3.  }  
  4.  public void setSex(char sex){  
  5.      if(sex!='F' && sex!='M'){  
  6.        throw new IllegalArgumentException("Invalid Sex");  
  7.      }  
  8.      this.sex =sex ;  
  9.  } 

(4)設(shè)置派生屬性
持久化類(lèi)并非所有屬性都直接和表的字段匹配,持久化類(lèi)的有些屬性是可以在運(yùn)行的時(shí)候得出的,這些稱(chēng)作派生屬性。正如之前的avgPrice屬性,該方案包括兩個(gè)步驟:

  • 在映射文件中不映射avgPrice屬性
  • 在Customer類(lèi)的setOrders()方法中加入程序邏輯,自動(dòng)為avgPrice屬性賦值。

除了這種方法來(lái)設(shè)置派生屬性,還可以如下解決:

利用元素的formula屬性。formula屬性用來(lái)設(shè)置一個(gè)SQL表達(dá)式,Hibernate將根據(jù)它來(lái)計(jì)算派生屬性的值。以Customer類(lèi)的totalPrice屬性為例:

 
 
 
 
  1.  

在Hibernate從數(shù)據(jù)庫(kù)中查詢(xún)Customer對(duì)象時(shí),若查詢(xún)totalPrice,即:

 
 
 
 
  1. select totalPrice from CUSTOMERS; 

使用formula屬性后,上面的查詢(xún)語(yǔ)句就會(huì)自動(dòng)地被替代成:

 
 
 
 
  1. select (select sum(o.PRICE) from ORDERS o where o.CUSTOMER_ID=1) from CUSTOMERS; 

如果子句的查詢(xún)結(jié)果為空,那么上述的語(yǔ)句就會(huì)出現(xiàn)異常。解決方法是:將totalPrice的屬性定義為Double包裝類(lèi)型。

(5)控制insert和update語(yǔ)句

Hibernate在初始化階段,就會(huì)根據(jù)映射文件的映射信息,為所有的持久化類(lèi)定義以下的SQL語(yǔ)句。

以上SQL語(yǔ)句中的“?”代表JDBC PreparedStatement中的參數(shù)。這些SQL語(yǔ)句都存放在SessionFactory的內(nèi)置緩存中,當(dāng)執(zhí)行Session的save()、update()、delete() 、load()和get()方法的時(shí)候,將從緩存中找到對(duì)應(yīng)預(yù)定義的SQL語(yǔ)句,再把具體的參數(shù)值綁定到該SQL語(yǔ)句中。

#p#

2、創(chuàng)建命名策略

還有一直一種方法是實(shí)現(xiàn)Hibernate的org.hibernate.cfg.NamingStrategy接口,對(duì)于這個(gè)接口Hibernate提供了兩種參考實(shí)現(xiàn)類(lèi):org.hibernate.cfg.defaultNamingStrategy和org.hibernate.cfg.ImprovedNamingStrategy類(lèi)。

MyNamingStrategy.java

 
 
 
 
  1. package mypack;  
  2. import org.hibernate.cfg.ImprovedNamingStrategy;  
  3. import org.hibernate.util.StringHelper;  
  4. public class MyNamingStrategy extends ImprovedNamingStrategy {  
  5.    public String classToTableName(String className) {  
  6.         return  StringHelper.unqualify(className).toUpperCase()+'S';//classname轉(zhuǎn)化成大寫(xiě)字母+S就是對(duì)應(yīng)的表名  
  7.    }  
  8.    public String propertyToColumnName(String propertyName) {  
  9.        return propertyName.toUpperCase();  
  10.    }  
  11.    public String tableName(String tableName) {  
  12.        return tableName;  
  13.    }  
  14.    public String columnName(String columnName) {  
  15.        return columnName;  
  16.    }  
  17.    public String propertyToTableName(String className, String propertyName) {  
  18.        return classToTableName(className) + '_' +  
  19.             propertyToColumnName(propertyName);  
  20.    }  

使用命名策略后可以更好的將數(shù)據(jù)庫(kù)中表名、列名對(duì)象化成類(lèi)中的對(duì)象。

#p#

3、實(shí)例

本節(jié)的代碼下載地址:http://down./data/326754

主要的BusinessService.java

 
 
 
 
  1. package mypack;  
  2.  
  3. import org.hibernate.*;  
  4. import org.hibernate.cfg.Configuration;  
  5. import java.util.*;  
  6.  
  7. public class BusinessService{  
  8.   public static SessionFactory sessionFactory;  
  9.   static{  
  10.      try{  
  11.        Configuration config = new Configuration()  
  12.              .setNamingStrategy( new MyNamingStrategy() )  
  13.              .configure();       //加載hibernate.cfg.xml文件中配置的信息  
  14.       sessionFactory = config.buildSessionFactory();  
  15.     }catch(RuntimeException e){e.printStackTrace();throw e;}  
  16.   }  
  17.  
  18.   public Customer loadCustomer(long customer_id){  
  19.     Session session = sessionFactory.openSession();  
  20.     Transaction tx = null;  
  21.     try {  
  22.       tx = session.beginTransaction();  
  23.       Customer customer=(Customer)session.get(Customer.class,new Long(customer_id));  
  24.       tx.commit();  
  25.       return customer;  
  26.     }catch (RuntimeException e) {  
  27.       if (tx != null) {  
  28.          tx.rollback();  
  29.       }  
  30.       throw e;  
  31.     } finally {  
  32.        session.close();  
  33.     }  
  34.   }  
  35.  
  36.   public void saveCustomer(Customer customer){  
  37.     Session session = sessionFactory.openSession();  
  38.     Transaction tx = null;  
  39.     try {  
  40.       tx = session.beginTransaction();  
  41.       session.save(customer);  
  42.       tx.commit();  
  43.  
  44.     }catch (RuntimeException e) {  
  45.       if (tx != null) {  
  46.          tx.rollback();  
  47.       }  
  48.       throw e;  
  49.     } finally {  
  50.        session.close();  
  51.     }  
  52.   }  
  53.  
  54.     public void loadAndUpdateCustomer(long customerId) {  
  55.       Session session = sessionFactory.openSession();  
  56.       Transaction tx = null;  
  57.       try {  
  58.         tx = session.beginTransaction();  
  59.         Customer customer=(Customer)session.get(Customer.class,new Long(customerId));  
  60.         customer.setDescription("A lovely customer!");  
  61.         tx.commit();  
  62.  
  63.     }catch (RuntimeException e) {  
  64.       if (tx != null) {  
  65.         tx.rollback();  
  66.       }  
  67.       throw e;  
  68.     } finally {  
  69.       session.close();  
  70.     }  
  71.   }  
  72.  
  73.   public void updateCustomer(Customer customer){  
  74.     Session session = sessionFactory.openSession();  
  75.     Transaction tx = null;  
  76.     try {  
  77.       tx = session.beginTransaction();  
  78.       session.update(customer);  
  79.       tx.commit();  
  80.  
  81.     }catch (RuntimeException e) {  
  82.       if (tx != null) {  
  83.          tx.rollback();  
  84.       }  
  85.       throw e;  
  86.     } finally {  
  87.        session.close();  
  88.     }  
  89.   }  
  90.  
  91.   public void saveDictionary(Dictionary dictionary) {  
  92.     Session session = sessionFactory.openSession();  
  93.     Transaction tx = null;  
  94.     try {  
  95.       tx = session.beginTransaction();  
  96.       session.save(dictionary);  
  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.  public void updateDictionary(Dictionary dictionary){  
  110.     Session session = sessionFactory.openSession();  
  111.     Transaction tx = null;  
  112.     try {  
  113.       tx = session.beginTransaction();  
  114.       session.update(dictionary);  
  115.       tx.commit();  
  116.  
  117.     }catch (RuntimeException e) {  
  118.       if (tx != null) {  
  119.         tx.rollback();  
  120.       }  
  121.       throw e;  
  122.     } finally {  
  123.       session.close();  
  124.     }  
  125.   }  
  126.   public Dictionary loadDictionary(long dictionary_id) {  
  127.     Session session = sessionFactory.openSession();  
  128.     Transaction tx = null;  
  129.     try {  
  130.       tx = session.beginTransaction();  
  131.       Dictionary dictionary=(Dictionary)session.get(Dictionary.class,new Long(dictionary_id));  
  132.       tx.commit();  
  133.       return dictionary;  
  134.     }catch (RuntimeException e) {  
  135.       if (tx != null) {  
  136.         tx.rollback();  
  137.       }  
  138.       throw e;  
  139.     } finally {  
  140.       session.close();  
  141.     }  
  142.   }  
  143.  
  144.   public void printCustomer(Customer customer){  
  145.       System.out.println("name:"+customer.getName());  
  146.       System.out.println("sex:"+customer.getSex());  
  147.       System.out.println("description:"+customer.getDescription());  
  148.       System.out.println("avgPrice:"+customer.getAvgPrice());  
  149.       System.out.println("totalPrice:"+customer.getTotalPrice());  
  150.   }  
  151.  
  152.   public void printDictionary(Dictionary dictionary){  
  153.       System.out.println("type:"+dictionary.getType());  
  154.       System.out.println("key:"+dictionary.getKey());  
  155.       System.out.println("value:"+dictionary.getValue());  
  156.   }  
  157.    public void test(){  
  158.       Customer customer=new Customer("Laosan","Zhang",'M',new HashSet(),"A good citizen!");  
  159.       Order order1=new Order("Order001",new Double(100),customer);  
  160.       Order order2=new Order("Order002",new Double(200),customer);  
  161.       customer.getOrders().add(order1);  
  162.       customer.getOrders().add(order2);  
  163.  
  164.       saveCustomer(customer);  
  165.  
  166.       customer=new Customer("Laowu","Wang",'M',new HashSet(),null);  
  167.       saveCustomer(customer);  
  168.  
  169.       customer=loadCustomer(1);  
  170.       printCustomer(customer);  
  171.  
  172.       customer.setDescription("An honest customer!");  
  173.       updateCustomer(customer);  
  174.  
  175.       loadAndUpdateCustomer(1);  
  176.  
  177.       Dictionary dictionary=new Dictionary("SEX","M","MALE");  
  178.       saveDictionary(dictionary);  
  179.  
  180.       dictionary=loadDictionary(1);  
  181.       dictionary.setValue("MAN");  
  182.       updateDictionary(dictionary);  
  183.  
  184.       dictionary=loadDictionary(1);  
  185.       printDictionary(dictionary);  
  186.  
  187.    }  
  188.  
  189.   public static void main(String args[]) {  
  190.     new BusinessService().test();  
  191.     sessionFactory.close();  
  192.   }  

原文鏈接:http://blog.csdn.net/yu422560654/article/details/7047661


網(wǎng)頁(yè)名稱(chēng):精通Hibernate:對(duì)象關(guān)系映射基礎(chǔ)
當(dāng)前地址:http://www.dlmjj.cn/article/dpsgjjs.html