java Play 1.2.4 findByID不适用于复合Id 1 年,3 月 Questions & Answers 219 我的DB表中有一个复合主键。findByID方法接受id并返回实体。我不知道如何实现这个接受复合Id并返回相应实体的方法 复合ID是使用@EmbeddedID注释实现的 请告诉我这件事
# 1 楼答案 若您使用的是嵌入式id,那个么必须重写对象的equals和hashCode方法 例子: 模型类: public class ModelClass extends GenericModel { @EmbeddedId public EmbeddedPK embeddedPK = new EmbeddedPK (); . . . } 嵌入式主键类: @Embeddable public class EmbeddedPK implements Serializable { //default serial version id, required for serializable classes. private static final long serialVersionUID = 1L; @ManyToOne @JoinColumn(name="col1_id",nullable=false,updatable=false) public Col1 col1; @ManyToOne @JoinColumn(name="col2_id",nullable=false, updatable=false) public Col2 col2; public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof EmbeddedPK)) { return false; } EmbeddedPK castOther = (EmbeddedPK)other; return (this.col1 == castOther.col1) && (this.col2 == castOther.col2); } public int hashCode() { final int prime = 31; int hash = 17; hash = hash * prime + ((int) (this.col1 ^ (this.col1 >>> 32))); hash = hash * prime + ((int) (this.col2 ^ (this.col2 >>> 32))); return hash; } } 通过上述方法,您可以生成嵌入式id并获取相应的实体 但另一种最佳方法是使用GenericModels GenerationType。汽车 例如: @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name = "entity_id") public Long id; 并通过在实体类上方添加下面的代码使列集唯一 @Table(name="example", uniqueConstraints=@UniqueConstraint(columnNames={"col_1", "col_2"})) }) 这种方法更容易获取相应的实体
# 1 楼答案
若您使用的是嵌入式id,那个么必须重写对象的equals和hashCode方法 例子: 模型类:
嵌入式主键类:
通过上述方法,您可以生成嵌入式id并获取相应的实体
但另一种最佳方法是使用GenericModels GenerationType。汽车 例如:
并通过在实体类上方添加下面的代码使列集唯一
这种方法更容易获取相应的实体
# 2 楼答案
关键是确定复合id的字符串表示形式
https://stackoverflow.com/a/19278569/1369495有一个例子可以为您指出正确的方向