嵌入式ID:主键和外键

时间:2015-01-24 13:25:10

标签: jpa

给定具有嵌入式ID和嵌入式外键的实体:

@Entity
public class One {

  @EmbeddedId
  private ModelId id;

  @Embedded
  @AttributeOverride(name = "id", column = @Column(name = "two_id"))
  private ModelId twoId;
}

@Embeddable
public class ModelId {

  private Integer id;
}

在JPQL中时:

SELECT o.id FROM One o WHERE o.twoId IN :twoId

然后JPA生成SQL:

SELECT id FROM one WHERE id IN (?)

而不是:

SELECT id FROM one WHERE two_id IN (?)

如何让它发挥作用?

1 个答案:

答案 0 :(得分:0)

将密钥放在ModelID实体中,并在实体One内使用它作为PK的引用:

@Entity
public class One {

@EmbeddedId
protected ModelId modelPK;

//getter and setter

}

public class ModelId {

  @column(name="id")//give the real column name
  private int id;

  @column(name="towID")//give the real column name
  private int twoId;

 //getters and setters      
}

然后使用以下JPQL查询:

SELECT o.modelPK.id FROM One o WHERE o.modelPK.twoId=:twoId