2015-06-25 32 views
0

在這裏,我們有:DAO持久性:只有一種方法來存儲複雜的數據對象?

public final class Product { 

Integer productId; 
String description; 
... 

public Product(final Integer productId, final String descripcion, ...) { 
    this.product_id = productId; 
    this.description = description; 
    ... 
} 

public Integer getProductId() { ... } 
public String getDescription() {...} 

... 

} 

一則:

public final ProductDetails { 

Integer productId; 
String serialNumber; 
... 
public ProductDatails(final Integer productId, final serialNumber, ...){ ... } 
public Intger getProductId() { ... } 
public String getSerialNumber { ... } 
... 

} 

因此,爲了建立其持續兩個類包含的數據DAO,問題是,如果它是一個很好的做法做如下:

public Interface IProductDAO { 

     public void saveProduct(final Product product); 
     public void saveProductDetails(final ProductDetails productDetails); 

    } 

或:

public Interface IProductDAO { 
public void saveProduct(final Product product, final ProductDetails productDetails); 

我一直在服用考慮到兩個類重構爲一個如下:

public final class Product { 

Integer productId; 
String description; 
ProductDetails productDetails; 
... 

public Product(final productId productId, final String description, final ProductDetails productDetails,...) { 

    if(productId!=productDetails.getProductId()) 
     throw new IllegalArgumentException("ProductID is not the same"); 

    ... 

} 

}

所以:

public Interface IProductDAO {    
     public void saveProduct(final Product product);        
} 

我想知道哪一個是最根據最佳軟件開發實踐的'自然'方法。如果還有其他方法,他們也會受到歡迎。

+0

我喜歡你的最後一個。 ProductDetails成爲產品的一部分似乎是合乎邏輯的。 – jrahhali

回答

0

Bertrand Meyer - Object Oriented Software Construction (2Ed),該類產品應包含對產品詳細的參考,因爲存在這些類之間的緊密關係。

另一方面,從產品類擴展到產生新的ProductDetails類是一種很好的做法。在這兩種情況下,一個DAO應該如下:

public void saveProduct(final Product product); 
0

最佳方法是你有兩個java類。一個是產品,第二個是ProductDetails,您可以在其中獲得產品的更多詳細信息。當用戶點擊產品時,您可以獲取此類以顯示此特定項目的更多詳細信息。

因此,需要在搜索頁面中顯示的最基本的細節可以進入產品類。

class Product { 

Integer productId; 
String description; 
@OneToOne 
@Basic(Fetch = FetchType.LAZY) 
ProductDetails details; 

public Product(final Integer productId, final String descripcion, ...) { 
    this.product_id = productId; 
    this.description = description; 
    ... 
} 


public Integer getProductId() { ... } 
public String getDescription() {...} 

... 

} 
class ProductDetails{ 
Integer productId;//any Id 
String description; 
//Storing a HD picture and other getters and setters 
} 
//details of the class 
} 
+0

我不考慮使用休眠或其他ORM。事實上,問題的關鍵是如何通過應對策略或設計模式來實現這種情況。 –

相關問題