2015-09-22 36 views
0

我們如何爲以下場景創建域類。如何將關聯列之一用作Grails中表的主鍵?

CREATE TABLE station 
(
    store_id integer NOT NULL, 
    pos_id integer NOT NULL, 
    CONSTRAINT pos_locations_pk PRIMARY KEY (store_id, pos_id) 
) 

CREATE TABLE header 
(
    id serial NOT NULL, 
    store_id integer NOT NULL, 
    pos_id integer NOT NULL, 
    .... 
    CONSTRAINT sales_transactions_pk PRIMARY KEY (id, store_id), 
    CONSTRAINT sales_transactions_pos_fk FOREIGN KEY (store_id, pos_id) 
     REFERENCES station (store_id, pos_id) 
) 

CREATE TABLE line_item 
(
    id serial NOT NULL, 
    sale_id bigint NOT NULL, 
    store_id integer NOT NULL, 
    ..... 
    CONSTRAINT transaction_lines_pk PRIMARY KEY (id, store_id), 
    CONSTRAINT transaction_lines_sale_fk FOREIGN KEY (sale_id, store_id) 
     REFERENCES header (id, store_id) 
) 

我開始爲下面的站域

class Station { 
    int storeId 
    int posId 

    static mapping = { 
     table "station" 
     id composite: ['storeId', 'posId'] 
     storeId column: 'store_id' 
     posId column: 'pos_id' 
    } 
    } 

和頭表

class Header { 
int id 
Station station 

static mapping = { 
    cache false 
    version false 
    table "header" 

    columns { 
     station { 
      column name: 'store_id' 
      column name: 'pos_id' 
     } 
    } 
    id composite: ['id', 'station.storeId'] // Where I have to use store_id alone from association column to be included as a part of composite key to header table 
} 
} 

和LINE_ITEM表

class LineItem { 
int id 
Header header 

static mapping = { 
    table "line_item" 
    columns { 
     header { 
      column name: 'sale_id' 
      column name: 'store_id' 
     } 
    } 
    id composite: ['id', 'header.station.storeId'] // something like this where I have to include store_id along from header table which instead from station table should be included as a part of composite key 
} 
} 

回答

1

的問題是有之間的不匹配表關係臀部由數據庫模式和域類中的關聯決定。

例如,有一個多到一個協會從,但在數據庫中規定:

  1. 明確多到一個關係從工作站,通過外鍵
  2. 和隱含多對一部首商店(表中未示出,但我假定存在),通過複合主鍵

相同的情況存在用於的LineItem

Grails實際上是無意中透露了一些有關數據庫模式的重要信息。沒有糖衣:有缺陷。如果意圖以簡單英語解釋爲...

  1. 一家商店可以有多個電臺。
  2. 一個站可以有多個標題。
  3. 標題可以有許多訂單項。

...那麼數據庫架構應反映:

  1. 一到多,從商店到車站
  2. 一個一對多的從站頭
  3. 一一對多項目

通過諸如架構,您的Grails域模型可以無縫地映射。簡要回答你的問題,你不能做你想做的事情,因爲Grails/Hibernate關聯是基於屬性而不是屬性的屬性。

不可改變的數據庫架構

如果數據庫架構不能是固定的,你必須放棄你的域類的關聯。您可以使域名類別略多於Row Data Gateway。但是這樣做會限制動態,地點,標準和HQL查詢的功能;沒有表/域連接。

如果你只需要只讀訪問,你就可以創建數據庫視圖,這裏是一個瘋狂的想法,可能無法連工作:建立你所需要的意見,然後將意見創建域類。

+0

假設這種情況。有許多實體商店,每個商店都有自己的標題表,其中id是按順序生成的。現在,所有這些標題數據都會被推送到集中式雲中,唯一的方法是您可以唯一標識它使用的是id和store_id,因爲可以在多個商店中生成相同的id。我可以將作爲標題的主鍵,但是這對於唯一標識具有pos_id的行並沒有意義,並且也與LineItem表一樣。 – gowtham

+0

該電臺如何適合這張照片?而且,你允許更改數據庫模式嗎? –

+0

對不起,其實在以前的評論站中沒有存儲過。是的,我可以編輯架構,但這會對其他許多事情產生巨大影響。我正在尋找建議,無需編輯架構。 – gowtham

相關問題