0

好吧,这里我有一个例子说明我正在尝试做的事情没有成功。对不起这个虚拟的例子。我有以下表格:

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"表中使用了复合键。我想要从 DB 中得到 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;
    }

谢谢你的时间!

4

1 回答 1

0

你的模型没有意义。SecondaryTable 不能是 OneToMany 关系。

您需要的是一个 OWNER 表,它定义了 OWNER_ID,(可能是名称等)

所有者将拥有 OneToMany 宠物,以及 OneToOne(或 ManyToOne、OneToMany?)House

宠物会有一个多对一到所有者和多对一到房子

House 会有 OneToMany to Pet 和 OneToMany?给所有者

要拥有自己的,您只需选择所有者,要获得他们的宠物,您只需访问它们即可。

于 2013-05-09T13:06:27.787 回答