2016-09-07 100 views
0

我在休眠取特定屬性處於休眠一一對多的關係

CustomerAccountEnduserOrderDetails.class

@Entity @Table(name="customer_account_enduser_order_details") 
public class CustomerAccountEnduserOrderDetails implements Serializable{ 

private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy=GenerationType.AUTO) 
@Column(name="id") 
private Long id; 

@ManyToOne(fetch=FetchType.EAGER) 
@JoinColumn(name = "product_id", insertable = false, updatable = false) 
private CustomerCmsProduct customerCmsProduct; 
} 

其次有兩個pojo班,one-to-many relationshipCustomerCmsProduct.class

@Entity 
@Table(name="customer_cms_product") 
@JsonIgnoreProperties(ignoreUnknown = true) 
public class CustomerCmsProduct { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    @Column(name="id") 
    private Long id; 

    @Column(name="name") 
    private String name; 

    @Column(name="offer_price") 
    private String offerPrice; 

    @Column(name="original_price") 
    private String originalPrice; 

    @Column(name="discount") 
    private String discount; 
} 

她e如果我取CustomerAccountEnduserOrderDetails類的對象,那麼我會得到CustomerCmsProduct類也,我的問題是,這裏我想CustomerCmsProduct的特定列(不是所有默認我收到全部)像只ID和originalPrice。

我怎麼能這樣做projection在這裏?

+1

爲什麼你需要複雜化hibernate的自動獲取策略?爲什麼不能將其更改爲另一個級別,將所有數據庫對象轉換爲UI中的Pojo級別? – VinayVeluri

+0

我dint得到你想說的,你可以給一個例子或提示,如何轉換在另一個層面,我在手動想我可以爲不需要的字段設置空值,但它是非常昂貴的,如果我加載100對象在一個時間 –

回答

1

在服務層或web服務層(如果這是一個web項目)創建兩個不同於@Entity的類作爲DTO(數據傳輸對象),它有助於將數據從一層傳輸到另一層。

public class CustomerAccountEnduserOrderDetailsPojo { 
    private List<CustomerCmsProductPojo> productPojoList = new ArrayList<>(); 
    // getter and setter 
} 

public class CustomerCmsProductPojo {} 

按照下面的步驟

  • 通過執行從服務層查詢檢索@Entity類數據。
  • 迭代所有字段並僅將必需字段複製到pojo層
  • 使用服務方法將數據公開到其他圖層。

這樣,我們可以避免更改自定義休眠行爲,因爲它與許多參數(如緩存,每次迭代觸發的一對多查詢)相關聯。

而且,在此圖層中執行所需的任何自定義。希望這是多層次的項目,你有不同層次的服務器不同的目的。

+0

好吧..但我想知道是否有任何註釋,我們可以指定特定的列,我們要檢索..迭代和複製是非常昂貴的,性能問題將在那裏。 –

+0

AFAIK,我們沒有任何。如果可以在許多地方重用,您可以創建基於'AOP'的自定義註釋。 – VinayVeluri