2012-05-17 17 views
0

我必須在objectdb中實現一個查詢,而且幾乎沒有任何想法。在objectdb中的查詢

的問題是編寫一個查詢其

Returns the collection of all laptops each of which has at least one 
      other laptop preinstalled with the same processor. 

我的筆記本電腦類是

public class Laptop { 

    String modelName; // key 
    int price;  // in dollars 
    boolean hasHDScreen; // has a HD Screen ? 
    int hardDriveCapacity; // in GB 

    Processor processor; // the preinstalled processor 
    Memory memory; // the preinstalled memory 
    Company madeBy; // the inverse of company.makeLaptops 
} 

和我的處理器類是

public class Processor { 

    String modelName; // key 
    float clockSpeed; // in gigahertz (GHz) 

    Company madeBy; // the inverse of Company.makeProcessors 
} 

而且我的函數定義看起來像下面

public static Collection<Laptop> sameProcessor(Query q) { 
     /* Returns the collection of all laptops each of which has at least one 
     * other laptop preinstalled with the same processor. 
     */ 
     q.setClass(Laptop.class); 
     q.setFilter("this.processor == "); 

    } 

我該如何實現它? SQL也可以。

謝謝

+0

你使用休眠? – ant

+0

@ant:沒有,只是JDOQL查詢 –

+0

@ant:但在hibernate中的查詢也可以很方便。因爲那樣我就可以嘗試將它轉換成JAVA,並因此轉換成ObjectDb查詢語言 –

回答

1

終於找到了這一個。這裏的

public static Collection<Laptop> sameProcessor(Query q) { 
     /* Returns the collection of all laptops each of which has at least one 
     * other laptop preinstalled with the same processor. 
     */ 

     Collection result = new HashSet<Laptop>(); 
     q.setClass(Laptop.class); 

     Collection allLaptops = (Collection) q.execute(); 

     Iterator it = allLaptops.iterator(); 

     while(it.hasNext()) { 
      Laptop currentLaptop = ((Laptop)it.next()); 
      Processor p = currentLaptop.processor; 
      if(p.installedOn(q).size()>=2) { 

       result.add(currentLaptop); 
      } 
     } 

     return (Collection<Laptop>)result;  
    } 

的方法使用installedOn定義的解決方案是以下:

public Collection<Laptop> installedOn(Query q) { 

    /* Returns the collection of all laptops on which the target memory 
     is preinstalled. Represents the inverse of Laptop.memory. 
    */ 
     Memory memory = this; 
     q.setClass(Laptop.class); 
     q.declareParameters("Memory m"); 
     q.setFilter("this.memory == m"); 
     Collection result = (Collection)q.execute(memory); 
     return (Collection<Laptop>) result; 

    } 

感謝。希望能幫助到你。