2013-05-08 52 views
0

好吧,在這裏我舉了一個我試圖做的但沒有成功的例子。對不起,這個虛擬的例子。我有以下表格:JPA:使用複合鍵從輔助表中檢索列表

CREATE TABLE HOUSE(
    HOUSE_NAME VARCHAR2(255), 
    OWNER_ID VARCHAR2(255), 
    PRIMARY KEY(FOLDER_NAME, USER_ID) 
); 

CREATE TABLE PET(
    HOUSE_NAME VARCHAR2(255) NOT NULL, 
    OWNER_ID VARCHAR2(255) NOT NULL, 
    PET_NAME VARCHAR2(255) NOT NULL 
); 

ALTER TABLE PET 
    ADD CONSTRAINT FK_PET_HOUSE 
    FOREIGN KEY(HOUSE_NAME, OWNER_ID) 
    REFERENCES HOUSE(HOUSE_NAME, OWNER_ID) 
    ON DELETE CASCADE; 

INSERT INTO HOUSE VALUES('House 1', 'Owner 1'); 
INSERT INTO HOUSE VALUES('House 2', 'Owner 1'); 
INSERT INTO HOUSE VALUES('House 3', 'Owner 1'); 

INSERT INTO PET VALUES('House 1', 'Owner 1', 'Dog'); 
INSERT INTO PET VALUES('House 1', 'Owner 1', 'Cat'); 
INSERT INTO PET VALUES('House 2', 'Owner 1', 'Duck'); 
INSERT INTO PET VALUES('House 3', 'Owner 1', 'Bird'); 

正如你看到的,我用我的"HOUSE"表中的複合鍵。我想要的是從數據庫得到的3個對象是這樣的:

Owner Id: Owner1 
House name: House 1 
Pets: [Dog, Cat] 

Owner Id: Owner1 
House name: House 2 
Pets: [Duck] 

Owner Id: Owner1 
House name: House 3 
Pets: [Bird] 

我一直在尋找一種方式來做到這一點,但我不知道如何將這些表的鏈接,檢索列表。我至今是:

@Entity 
@Table(name="HOUSE") 
@SecondaryTable(name="PET", pkJoinColumns={ 
     @PrimaryKeyJoinColumn(name="HOUSE_NAME", referencedColumnName="HOUSE_NAME"), 
     @PrimaryKeyJoinColumn(name="OWNER_ID", referencedColumnName="OWNER_ID"), 
}) 
public class HousePets implements Serializable { 

    @Id 
    @Column(name="HOUSE_NAME") 
    private String houseName; 

    @Id 
    @Column(name="OWNER_ID") 
    private String ownerId; 

    @Column(table="PET" name="PET_NAME") //DON'T REALLY KNOW HOW TO DEAL WITH IT 
    private Set<String> petsSet = new HashSet<String> 

    //GETTERS AND SETTERS 
} 

,並檢索列表我使用的方法是這樣的:

public List<HousePets> getFoldersList() { 
     em = emf.createEntityManager(); 
     Query q = em.createQuery("SELECT h FROM HousePets h WHERE h.ownerId = :ownerId"); 
     q.setParameter("ownerId", "Owner 1"); 
     List<HousePets> result = q.getResultList(); 
     return result; 
    } 

感謝您的時間!

回答

0

您的模型沒有意義。 SecondaryTable不能是OneToMany關係。

你需要的是一個主表,定義OWNER_ID,(也許是名稱等)

業主將有一對多到寵物,和OneToOne(或多對一,一對多?)地府

寵物會有一個ManyToOne所有者和ManyToOne到房子

房子會有OneToMany寵物和OneToMany?給所有者

要得到一個自己的,你只需選擇所有者,讓他們的寵物,你只是訪問它們。