我在为我在数据库中使用的复合键编写泛型类时遇到问题。所有使用复合键的表都有关系 ManyToOne 并使用 2 FK。我写了以下课程:
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.ManyToOne;
@Embeddable
public class CompositeKey<K, T> implements Serializable {
@ManyToOne
K firstKey;
@ManyToOne
T secondKey;
public CompositeKey() {
}
public CompositeKey(K firstKey, T secondKey) {
this.firstKey = firstKey;
this.secondKey = secondKey;
}
public K getFirstKey() {
return firstKey;
}
public void setFirstKey(K firstKey) {
this.firstKey = firstKey;
}
public T getSecondKey() {
return secondKey;
}
public void setSecondKey(T secondKey) {
this.secondKey = secondKey;
}
@Override
public String toString() {
return "CompositeKey [firstKey=" + firstKey + ", secondKey="
+ secondKey + "]";
}
@Override
public int hashCode() {
/* HashCode implementation */
}
@Override
public boolean equals(Object obj) {
/* */
}
}
以及带有 CompositeKey 的示例类:
import javax.persistence.AssociationOverride;
import javax.persistence.AssociationOverrides;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
@Entity
public class TestClass {
@EmbeddedId
@AssociationOverrides({
@AssociationOverride(name = "firstKey", joinColumns = @JoinColumn(name = "FirstTable")),
@AssociationOverride(name = "secondKey", joinColumns = @JoinColumn(name = "SecondTable")) })
private CompositeKey<A, B> compositeKey;
@Lob
private String description;
/* Getters and Setters */
}
现在的问题是:
1.这种方法正确吗?还是为每个实体编写单独的复合键更好?
2.如果这种方法是正确的,那么我如何将annonation @ManyToOne 从 CompositeKey 类移动到 TestClass ?
3. 这种情况下可以使用级联吗?当保存具有复合键的实体时,我想保存复合键中的实体。
提前感谢您的回复!