Java 重头戏1.2.4 findByID不适用于复合Id
我的DB表中有一个复合主键。findByID方法接受id并返回实体。我不知道如何实现这个接受复合Id并返回相应实体的方法 复合ID是使用@EmbeddedID注释实现的Java 重头戏1.2.4 findByID不适用于复合Id,java,playframework,crud,playframework-1.x,Java,Playframework,Crud,Playframework 1.x,我的DB表中有一个复合主键。findByID方法接受id并返回实体。我不知道如何实现这个接受复合Id并返回相应实体的方法 复合ID是使用@EmbeddedID注释实现的 请让我知道这一点。如果您使用的是嵌入式id,那么您必须重写对象的equals和hashCode方法 例子: 模型类: public class ModelClass extends GenericModel { @EmbeddedId public EmbeddedPK embeddedPK = new EmbeddedPK
请让我知道这一点。如果您使用的是嵌入式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.AUTO。
例如:
并通过在实体类上方添加下面的代码使列集唯一
@Table(name="example", uniqueConstraints=@UniqueConstraint(columnNames={"col_1", "col_2"}))
})
这种方法更容易获取相应的实体。关键是确定复合id的字符串表示形式 有一个例子可以为您指出正确的方向
@Table(name="example", uniqueConstraints=@UniqueConstraint(columnNames={"col_1", "col_2"}))
})