JPA:使用复合键从辅助表中检索列表

时间:2013-05-08 21:04:26

标签: java jpa composite-key

好吧,在这里,我有一个例子,说明我没有成功的事情。抱歉这个虚拟的例子。我有以下表格:

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;
    }

谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

你的模型毫无意义。 SecondaryTable不能是OneToMany关系。

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

所有者会有一个OneToMany到Pet,OneToOne(或ManyToOne,OneToMany?)到House

Pet将拥有ManyToOne给所有者和ManyToOne到House

House会有一个OneToMany到Pet和OneToMany吗?对所有者

要获得一个拥有者,您只需选择所有者,即可获取他们的宠物。