0

我的数据库表中有一个复合主键。findByID 方法接受 id 并返回实体。我不确定如何实现此方法来接受复合 Id 并返回相应的实体。

复合 ID 是使用 @EmbeddedID 注释实现的。

请让我知道这一点。

4

2 回答 2

0

如果您使用的是嵌入式 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。例子:

    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "entity_id")
public Long id; 

并通过在您的实体类上方添加以下代码来使您的列集独一无二

  @Table(name="example", uniqueConstraints=@UniqueConstraint(columnNames={"col_1", "col_2"}))
  })

这种方法更容易获取相应的实体。

于 2013-09-30T09:44:59.273 回答
0

关键是为您的复合 ID 确定一个字符串表示形式。

https://stackoverflow.com/a/19278569/1369495有一个示例可能会为您指明正确的方向。

于 2013-10-09T19:08:24.320 回答